Cameron Cameron - 3 months ago 19
Javascript Question

jQuery Window Load not firing when called from within function

Using jQuery the following would log that the app had loaded once the DOM and all assets had been downloaded by the browser:

$(window).load(function() {

console.log('app loaded');

});


However I don't want this check to happen until after some other things have run.

So for example:

function checkLoaded()
{
$(window).load(function() {

console.log('app loaded');

});
}


So let's say I call this function after a bunch of other functions.

The problem is, because
$(window).load(function()
is an event listener, when I call the
checkLoaded()
function the event won't ALWAYS run (because it MAY have already been fired because everything has downloaded BEFORE the
checkLoaded()
function has run).

Any ideas on how I can do this?

I tried this:

function checkLoaded()
{
if(loaded)
{
console.log('app loaded');
}
else
{
checkLoaded(); // keep checking until the loaded becomes true
}
}

$(window).load(function(){

loaded = true;

});


But the problem here is that the checkLoaded function COULD get called hundreds of times in a few seconds and isn't a nice way of handling this.

UPDATE: The function is called using checkLoaded(); Just so everyone knows I am calling the function!

UPDATE 2:

The plan is essentially this:

function init() {

start();

}();

function start() {

// Show Preloader... and other stuff

/// Once all logic has finished call checkLoaded

checkLoaded();

}

function checkLoaded() {

if(loaded) {

show();

}

}

function show() {

... // show app

}


So I should be able to know if the status of loaded is true, but keep checking until it becomes true as it may be true or false when I get to the checking stage.

Answer

You run it either on window load or if it's already done using such kind of code:

function onLoad(loading, loaded) {
    if (document.readyState === 'complete') {
        return loaded();
    } 
    loading();

    if (window.addEventListener) {
        window.addEventListener('load', loaded, false);
    } else if (window.attachEvent) {
        window.attachEvent('onload', loaded);
    }
}

onLoad(function() {
    console.log('I am waiting for the page to be loaded');
}, function() {
    console.log('The page is loaded');
});