When browser starts to load a web page, document.readyState===loading. When DOM is constructed, document.readyState==interactive. When page is fully loaded, i.e., the images/css are all loaded, document.readyState===complete.
After document.readyState becomes interactive, the DOMContentLoaded event is about to fire. After document.readyState becomes complete, the load event is about to fire.
The function as the parameter of the jQuery function $(document).ready(function) will be executed after DOM is constructed, i.e., after document.readyState becomes interactive. This function is not event driven, specifically, not driven by the DOMContentLoaded event. Some browsers may not implement the DOMContentLoaded event, but the function in $(document).ready(function) is always executed. Typically, the DOMContentLoaded event is fired after the function in $(document).ready(function) is called.
$(function function(){}) is the same as $(document).ready(function). The function will be called after the document has finishing loading and been parsed. If you use both, both functions will be executed, in the order of the execution of the two statements.
Then, the DOMContentLoaded event is fired at document and bubbled to window. You can use document.addEventListener and window.addEventListener to listen to the DOMContentLoaded event.
After all images/css files/sub-frames are loaded, the load event is fired. You have quite a few methods to listen to load event.
- window.onload=function handler(){};
- <body onload=”handler();”>
- window.addEventListener(“load”,handler);
- document.body.onload=function handler(){};
Note that use window.onload not document.onload. The load event is fired/dispatched on the window object(although event.target is set to document), not the document object, so document.onload will never be triggered. The body element exposes as event handler content attributes a number of the event handlers of the Window object, so setting document.body.onload is the same as setting window.onload. Don’t use document.body.addEventListener(“load”,handler) as this event isn’t fired on document.body and the handler will never be called. If you set the onload property using window.onload, document.body.onload, <body onload=…> for multiple times, the last handler you set will override previous ones and only one handler survives. The difference between window.load and window.addEventListener(“load”,handler) is that the latter can bind multiple event listeners to the load event(all of them will be called when the load event occurs), and these listeners co-exist with the onload event handler.