$(window).on("load") not triggered in postRender

98 views Asked by At

I have a jquery code that I have to trigger after the page is loaded, I am doing it in postRender function call of the view, but postRender and window load event are totally async, so, the window load event might happen before I am in postRender adding the listener for the load event, is there any replacement for the function in this case, or am I missing something?

thanks for the help

1

There are 1 answers

0
spenibus On

You could use a flag to keep track of the window.load event in the global scope and choose an execution path in postRender() based on the status of the flag.

// define this in the global scope
var windowHasLoaded = false;
$(window).on('load', function(){
    windowHasLoaded = true;
});

Then in view.postRender():

// window has already loaded, just run now
if(windowHasLoaded) {
    doStuff();
}
// run on window load event
else {
    $(window).on('load', doStuff);
}

var doStuff = function() {
    // the stuff to do
}