Parashuram
Parashuram

Reputation: 1569

window.onload and document.ready : execution order in case specified multiple times

We all know that we can use document.ready many times and they will be executed one by one in the order as mentioned in script.

Also we know that we can use window.onload only once.

The question here is, what will happen if we use window.onload ? is this error or the first one will be executed and rest are ignored or last one will be executed and rest are ignored?

Upvotes: 2

Views: 1203

Answers (3)

Canvas
Canvas

Reputation: 5897

jsFiddle : https://jsfiddle.net/CanvasCode/ouk7aatj/

the last onload will be fired and all previous onload statements will be ignored

window.onload= function() {
  alert("Onload 1");
};

window.onload= function() {
  alert("Onload 2");
};

var i = 0;

window.onload= function() {
     i = 10;
  alert(i);
};

window.onload= function() {
    i++
  alert(i);
};

Output : 1

You can attach a function to the window.onload event listener like so if you want it to "act" the same as document.ready

jsFiddle : https://jsfiddle.net/CanvasCode/ouk7aatj/1/

window.addEventListener('load', function (){
    alert('Function #1');
});

window.addEventListener('load', function (){
    alert('Function #2');
});

Upvotes: 3

Daniel Schmidt
Daniel Schmidt

Reputation: 11921

The reason is that $(document).ready(fn) is a function provided by jQuery, which takes a function and adds it to a queue which gets executed when the document is ready.

On the other hand window.onLoad is a property on the window object, which gets called by the browser when the page is loaded. Therefore it gets overwritten if you access it twice. You may build something similar as the interface of $(document).ready(fn) if you do something like that:

window.onLoadQueue = []

window.onLoad = function() {
    window.onLoadQueue.forEach(function(fn) {
        fn()
    });
};

window.addOnLoad = function(fn) {
    // TODO: test if fn is a function
    window.onLoadQueue.push(fn);
}

Upvotes: 1

Matthias Van Parijs
Matthias Van Parijs

Reputation: 271

At first, there are fundamental differences between $(document).ready(...) and window.onload. The first one occurs after the HTML document has been loaded, the native onload occurs when the window has loaded, meaning resources (images, ...) are also loaded.

Take the following example:

window.onload = function () { console.log(1); }
window.onload = function () { console.log(2); }

Meaning the first function gets overwritten by pointing to the second function. The output will be 2 in your console, and console.log(1) will never be executed.

Your jQuery on the other hand:

$(document).ready(function () { console.log(1); });
$(document).ready(function () { console.log(2); });

Both functions will be called and the output will be both 1 and 2.

Upvotes: 2

Related Questions