Difference Between document.ready() vs window.onload()

Difference Between document.ready() vs window.onload()


ready-vs-onload

As front-end developers, we face the situation of doing something when the page loads the very first time. But there are a lot of ways to do it and confusion arises about what to use and what not to use. So today we will see all the different possible ways and their pros and cons as well.

Today's Agenda


Q01. How can you check whether an HTML page is loaded or not?
Q02. What is the document.ready() function?
Q03. What is (window).on("load") function? How it is different from the ready function?
Q04. What is the difference between window.onload() vs. DOMContentLoaded event?
Q05. What is the window.onload() function?
Q06. What is the difference between $(document).ready(), window.onload() and $(window).load() methods?
Q07. What is the difference between window.addEventListener() vs window.onload() function?
Q08. What is the difference between window.onload and document.ready() methods?
Q09. When does window.onload triggers with Lazy Loaded Images and Scripts?


Introduction


If you place your JavaScript DOM manipulation code or any JS code that depends on your DOM elements in the head section of your HTML page, this code executes before your DOM is fully ready so weird errors and things may happen.  

So you have to make sure to wrap your code inside special callbacks that fire only when your DOM is fully loaded. But if you place any JavaScript code after the body element, your code will be executed after your DOM is fully loaded so you don’t have to worry about wrapping your code inside any callbacks.

Q01. How can you check whether an HTML page is loaded or not?

There are two most popular ways used to make functions work when a page loads:

1. JavaScript’s window.onload function
2. jQuery’s $(document).ready() method

Apart from this, there are other different ways as well to do the same things.


Q02. What is the document.ready() function?

A page can not be manipulated safely until the DOM is ready. The ready event occurs when the DOM has been loaded. The jQuery detects this state of readiness for you. The ready() event is fired after the document is ready.

The ready waits only for the HTML elements and tags. However, it does not wait for the content such as images or videos, etc. The ready() method, gets executed only when the ready event is triggered. 

The $(document).ready() is a jQuery method that executes a block of code when the DOM has been loaded. The code included inside $( document ).ready() will run only once the page DOM is ready for JavaScript code to execute neglecting the loading of images and other contents on the website. The ready() method is used to specify what happens when a ready event occurs. 

 <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

$(document).ready(function(){
    alert("document.ready function is called!");
});

Please note that the jQuery library should be included and loaded first before the ready method otherwise it will never be executed. 

Here the parameter "function" is required. It is a callback function or the event handler where you put the code that you want to execute after the DOM has finished loading. You can also pass a named function to the ready() instead of passing an anonymous function.

The shorthand version of the above code can also be used for checking the document.ready(). 

$(function() {
    alert("DOM is ready!");
});


Q03. What is (window).on("load") function? How it is different from the ready function?

It is a jQuery method to check the window load event. It is always executed after the document ready function. 

The load event is fired when the entire page is loaded, including all the dependent resources such as stylesheets, scripts, iframes, and images. This is in contrast to the JavaScript's DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. This event is non-cancelable and does not bubble.

Unlike document.ready(), the code included inside $( window ).on( "load", function() { }) will execute only once when the entire page ( including images or iframes) is loaded, not just the DOM, is ready.

function OnWindowLoad(){
    alert("Window is loaded successfully!");
}
$( window ).on( "load", OnWindowLoad );


Q04. What is the difference between window.onload() vs. DOMContentLoaded event?

The Javascrit's DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. The DOMContentLoaded is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

A DOMContentLoaded is dispatched to the document when all the HTML has been parsed and run. The event bubbles to the window. It doesn't wait for stylesheets, images, and subframes to finish loading. 

document.addEventListener("DOMContentLoaded", function(event) {
    alert("DOMContentLoaded event triggered!");    
});

On the other hand, the window.onload() is invoked when the entire page has loaded, including all dependent resources such as stylesheets, scripts, iframes, and images. It waits until the last resource is loaded.

$(window).on('load', function() {
    alert('Window is loaded and all the assets are loaded!')
})

Q05. What is the window.onload() function?

The window.onload is the event property that represents the load event of the window object. The JavaScript window load event is fired when the entire web page is loaded on the browser. 

It waits for all the DOM elements and the contents, including all the dependent resources like HTML tags, stylesheets, scripts, images, videos, etc.

All events named load will not propagate to Window, even with bubbles initialized to true. To catch load events on the window, that load event must be dispatched directly to the window.

The onload method can be implemented using various syntax:

1. By JavaScript Onload Function:

window.onload = function(){
        alert('Window.onload function is triggered!');
};

2. By JavaScript addEventListener() event:

window.addEventListener("load", (event) => {
    alert('load event is triggered!');
});

3. By HTML Body onLoad event:

function OnWindowLoad(){
    alert("Window is loaded successfully!");
}

<body onLoad="OnWindowLoad();">
 <h1>jQuery Demo</h1>
</body>

Q06. What is the difference between $(document).ready(), window.onload() and $(window).load() methods?

All of the above-said methods can be used to check whether the DOM is fully loaded and ready to be manipulated by your JavaScript code.

The main difference among them is that $(document).ready() and $(window).load() are jQuery methods, i.e. not pure JavaScript methods so to use them you need to include jQuery library.  But window.onload is a pure JavaScript method that you can use without any external libraries.

$(document).ready(function(){
    alert("document.ready function is called!");
});

$(document).ready() function uses either the modern browser API event DOMContentLoaded to check if the DOM is ready or readyState document variable in older browsers which makes it the best candidate if you need to check if your DOM is fully loaded and ready. 

window.onload = function(){
    alert('Window.onload function is triggered!');
};

On the contrary $(window).load() and window.onload are created to check if the page and its resources (images, texts, stylesheets, JavaScript) are fully loaded.  So if you just want to check if the DOM is ready it may be slower than $(document).ready() function.

$(window).on('load', function() {
    alert('Window is loaded and all the assets are loaded!')
})

Q07. What is the difference between window.addEventListener() vs window.onload() function?

Both are the events which triggered when the page is fully loaded. But there is a big difference that matters when you are creating large projects. 

The key difference between them is that, window.onload event will be called only once, and it will override the previously attached onload event i.e. the event handler defined later overwrites the previous one.

On the other hand, in the window.addEventListener you can add as many functions as you want and they will all be called in parallel. The addEventListener events will be executed in the order they are defined.

// Using window.onload event twice
window.onload = function () {
    console.log("window.onload action-1 executed");
};
 
window.onload = function () {
    console.log("window.onload action-2 executed");
};
 
// Using window.addEventListener event twice
window.addEventListener("load", function () {
    console.log("addEventListener action-1 executed");
});
 
window.addEventListener("load", function () {
    console.log("addEventListener action-2 executed");
});

If you see the output of the above code, only the second window.onload function will be executed while, both the addEventListener methods will be executed.

window-load

This is because the window.onload is an attribute, like a variable. So when you use this event 2nd time, then its previous function is replaced by the new one. You can notice that the syntax is window.onload = function () {} which means that it is an attribute whose value can be replaced.

On the other hand, window.addEventListener you can see that it is a function that has two parameters. So when you call this event and pass your function in the second parameter, it will be placed in a stack of “load” events. That is why all functions of addEventListener are called without overriding.

It is highly recommended that you should make a habit of using the window.addEventListener as it is more reliable. Because it happens sometimes that your window.onload function is not being called and you wonder why it is not being called, and the reason is simple: “Somewhere else in the code this attribute is being overridden by another function”.

Q08. What is the difference between window.onload and document.ready() methods?

The main difference between JavaScript’s window.onload and jQuery’s $(document).ready(function) method is that:

While the document.ready is a jQuery event which means that it is only available in the jQuery library, the window.onload is a pure JavaScript event, and therefore, available in most browsers and libraries.

The window.onload event waits for all the resources, contents, CSS, and JavaScript unlike $(document).ready(). So, if you have an image or a video that takes a lot of time to load window.onload will wait for it to finish its loading, and during that time, none of the code inside it will get executed.

window.onload = (event) => {
  alert('Window.onload event is triggered!');
};

On the other hand, $(document).ready() won’t wait for it and load the script once the DOM is ready. However, if the script contains code that operates on an image or a video, such as finding the height and width of the image, $(document).ready() might result in false values as the image might not have finished loading. In this case, window.onload is preferred.

$(function() {
    alert("DOM is ready!");
});

You can only define only one event handler for the window.onload event because the last one overrides the previously defined onload methods. However, you can have several event handlers for the ready event.

The ready methods will executed in the order they are defined. On the other hand, the event handler defined later overwrites the previous one. Therefore, only the second one will be executed.

Q09. When does window.onload triggers with Lazy Loaded Images and Scripts?

Will window.onload trigger if the browser is waiting for a lazy loaded image to be triggered to load?

Actually, the window.onload event is fired after the required image and script elements are loaded not after all the elements are loaded even though they are told to not load yet.

Depending on the screen size, browser, etc. the browser may decide to load the lazy-loaded images on the initial page load. In that case, it will fire the window.onload event after those are loaded.

window.onload = (event) => {
  alert('Window.onload event is triggered!');
};


Recommended


Thanks for visiting this page. Please follow and join us on LinkedIn, Facebook, Twitter, Telegram, Quora, Instagram, WhatsApp, Tumblr, VK, Pinterest, and YouTube for regular updates.

2 Comments

Please do not attach any link in the comment box.

Previous Post Next Post