Home > front end >  How to load page completely before proceeding with Javascript?
How to load page completely before proceeding with Javascript?

Time:12-21

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 ><?= 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

CodePudding user response:

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.

  • Related