Window.onload vs onDocumentReady in javascript


In JavaScript, window.onload and document.ready() are the methods used when the page is being loaded.

Window.onload

The window.onload method gets executed after the entire web page is loaded. This includes all the elements related with DOM like the head tag, tittle tag and all the other tags including the style sheets, images and videos. The onload method is used by passing a function to it. The called function will be executed after the object is loaded.

Syntax

This is the syntax of onload method −

Window.onload = function()
Window.onload = (event) => {} //arrow function

Example 1

This example demonstrates how the window.onload works in JavaScript −

<!DOCTYPE html> <html lang="en"> <head> <title>window.onload()</title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <script> window.onload = (event) => { console.log("The first call will not be loaded if there are two window.onload calls"); }; window.onload = (event) => { console.log("The second call is loaded while using window.onload"); }; </script> </head> <body id="body"> <h1>window.onload()</h1> </body> </html>

Output

This is the output displayed in the console when the above code is executed −

The second call is loaded while using window.onload

In the above example, there are two calls of the window.onload function. But it is displays the content of the second call only. As this is the case that when window.onload is used the content will be loaded when the page is being loaded directly.

Windows.ready

So if there is a possibility that there will be more calls of window.onload function then the last one will be executed. When the DOM (document object model) has loaded, the ready event takes place.

The best place for all other jQuery events and functions to be is in this event since it happens after the document is ready. like in the example explained below. What happens when a ready event takes place is specified by the ready() method is mentioned below.

Syntax

Windows.ready function syntax is as follows −

$(document).ready(function () {
   //statements.
});
< body onload= " " > and the ready() method shouldn't be used together.

Example

This example demonstrates how the onDocumentReady works in JavaScript −

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $("button").click(function () { $("p").slideToggle(); }); }); </script> </head> <body> <p>onDocumentready is used, then after the document is loaded then the functionality will be shown which reduces the errors </p> <button>Click to hide</button> </body> </html>

Advertisements