Downloading JavaScript files or long JavaScript blocks and then executing it when it has been downloaded slows the download of the whole page. One way to circumvent this is to execute the JavaScript when the page has loaded.
On window load
It is very common to load a script when the page has downloaded. When all the content, including other JavaScript and image files has downloaded the window loaded event is triggered. If there is any JavaScript within the appropriate event handler, the browser will trigger and execute it.
The window.onload
event handler
will execute when this happens:
window.onload = function(){ console.log("Hello world") }
This code will therefore not run until everything on the page is fully loaded. The benefit of this is that if another script or library (for instance jQuery) needs to be loaded and executed before this script can be run (for instance, if this script relies on a function or variable from that script) then it will wait until that script has finished loading.
Multiple functions on load
But what about multiple functions being loaded? The above example will only load that one function and setting it to a different value will overwrite what was already put into the value. To understand this, look at this sample:
var x = function(){ console.log("Hello world") } x = function(){ console.log("Hello everyone") } x();
The variable x
is set up with two values, but the first one is overriden by the second assignment, thus
when x
is called it is called with the second function instead of the first.
The same issue occurs with the window object. So the fix is to add an event handler.
var f = function() { console.log('Loaded'); }; if(window.addEventListener){ window.addEventListener('load', f) } else { window.attachEvent('onload', f) }