PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 8, 2022

[FIXED] How to load page completely before proceeding with Javascript?

 January 08, 2022     custom-fields, javascript, wordpress     No comments   

Issue

Sorry if the title is a bit tricky to understand. Allow me to elaborate.

On my Wordpress website, I recently started using the extension Custom Field Suite, in order to be able to create custom fields. It allows me to retrieve those afterwards in html, so that if I ever need to change a text I can do it directly on Wordpress instead of having to pull up the html files and re-upload them every time.

Today I was doing some Javascript and I needed to retrieve a text that comes from one of those custom fields. Basically retrieve something like this :

<h1 class="title"><?= CFS()->get('title'); ?></h1>

So, what I thought of doing was using a QuerySelector and retrieve the class .title into a variable, like so :

let sentence = document.querySelector(".title");

The only problem is that it returns undefined, and I think I know why. When I load the page up and then go into the console and type exactly that, it works, which leads me to believe my Javascript retrieves the title faster than it has time to be returned by the CFS()->get.

My problem now is that I don't know how I could make it so that my title loads in time for the Javascript to proceed it, so I was wondering if anyone out there had an idea.

Thanks in advance


Solution

You can use the window.onload function of Javascript:

window.onload = function() {
    alert('Page is loaded');
};

Or you can use an event listener:

window.addEventListener("load", function() {
    alert('Page is loaded');
});

Be sure to put your js inside the functions. Be aware that this is one of many possibilities, so you can surely research for more options.



Answered By - EduardoK
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing