There were quite a few answers with different methods to delay the execution of the script, with some inconsistencies in the comments, so I wrote a little DEMO to compare what the real differences of all these approaches are, because they are certainly not equivalent.
For impatient people who do not want to see a demo, here are the most important things to keep in mind choosing the right tool for the job:
window.onload = function () {...};
- it works in all browsers
- deletes all previous handlers
- it only starts after loading all images.
window.addEventListener ("load", function () {...});
- it does not work in internet explorer
- it only starts after loading all images.
jQuery (document) .ready (function () {...});
- it works in all browsers
- it starts as soon as the DOM is ready
Just for the curious, this is exactly what jQuery does to make sure your handlers are running as soon as the DOM is ready and running in browsers:
// Handle when the DOM is ready ready: function( wait ) { // A third-party is pushing the ready event forwards if ( wait === true ) { jQuery.readyWait--; } // Make sure that the DOM is not already loaded if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket
I show as an example that something that seems simple as a document handler can be quite complicated if you need it to work in all browsers and not freeze your scripts if some image or advertisement loads with a delay .
source share