Is <body> .onLoad called before rendering?
I want to call some JS after the page loads, this may mean a delay, and so I first want the page to load so that the content is shown ... but it seems that the code in the onLoad handler is called before rendering is complete. Is there a better event that I can use that fires when the page is “completed”?
To clarify, I want to start JS after the page is displayed on the screen, so there really is a “post-everything event”.
There are several points of interest in the time sequence. This general sequence is a good overview, although different browsers and versions implement the details a little differently. (It is assumed that you are using raw Javascript and you need to minimize cross-browser issues, as well as comprehensive internal handling of cross-server issues. JQuery is slightly different):
T0] page-started-- The browser started working on the page, but the rest of the environment is in motion. Your JS operations may occur in the wrong context and simply be deleted when the correct context stabilizes. You probably don't want to try to execute any kind of JS at all.
T1] onLoad-- [ : addEventListener ( ""..., window.onload =... ..]. . , , . ( , "" "", "" "".)
JS-, . , , HTML [getElementById (..., appendChild (... ..), , - , .
T2] DOM- - . JS <script> ... </script> HTML, </body> . , DOM <body> . , 99% . , ( , JQuery).
T3] DOM-ready-- [ : addEventListener ( "DOMContentLoaded"..., window.ondomcontentloaded =... ..] HTML , JS - 100% , HTML [getElementById (..., appendChild (... ..).
T4] Render-done - . - - . , , , . , DOM, "", , , , . , , , , - , JS-; (T3] DOM-ready) .
window.onload = function(){
// your code here
};
( , ).
( body). HTML.
FWIW, jQuery. , IE , window.onload :
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}