Difference between document.ready and window.onload or pageLoad

Difference between document.ready and window.onload or pageLoad

26 Mar 2024
Advanced
18.3K Views
12 min read

document.ready vs window.onload or pageLoad: An Overview

We think pageLoad() and jQuery’s $(document).ready() events do the same. Both methods seem too similar in simple demo example. But $(document).ready() and pageLoad() methods are very much different in functioning. In this Tutorial, we will know more about What is $(document).ready()?, What is pageLoad()? and basic Difference between document.ready and pageLoad. For more comprehensive explanation of different concepts of ASP.NET, get yourself enrolled in our ASP.NET Certification Training.

Read More: Top 50 ASP.NET Core Interview Questions and Answers for 2024

What is $(document).ready()

JQuery’s document.ready() method gets called as soon as DOM is ready (means browser has parsed the HTML and built the DOM tree). It is cross browser compatible means behave equally on all browsers. If your web page has large images, it will not wait for loading of images completely. Hence it may called before pageLoad() method. We can have multiple document.ready() methods on a web page that will be called in coming sequence.
<script type="text/javascript">
$(document).ready(function(){ 
 // Gets called as soon as DOM is ready
 //code here
 }); 
 </script> 

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Ready Example</title>
    <!-- Include jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        // This code will be executed when the DOM is fully loaded and ready
        $(document).ready(function() {
            // Code to execute once the DOM is ready
            console.log("Document is ready. You can manipulate the DOM here.");
            // For example, let's change the text of an element with id="example"
            $("#example").text("Hello, world!");
        });
    </script>
</head>
<body>
    <div id="example">Original Text</div>
</body>
</html>    

What is pageLoad()

pageLoad() method gets called when images and all associated resources of the page have been fully loaded. Suppose your web page has large size images then until all the images are not fully loaded on the page, pageLoad() method will not called. pageLoad() method is not browser compatible. We can have only one pageLoad() method on a web page.

<script type="text/javascript">
function pageLoad() 
 {
 // gets called when page have been fully loaded
 //code here 
}
 </script> 

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Load Example</title>
    <script>
        // Define a custom pageLoad function
        function pageLoad() {
            // Code to execute once the page is fully loaded
            console.log("Page is fully loaded. You can manipulate the DOM here.");
            // For example, let's change the text of an element with id="example"
            document.getElementById("example").innerText = "Hello, world!";
        }
    </script>
</head>
<body onload="pageLoad()"> <!-- Call the pageLoad function when the page is loaded -->
    <div id="example">Original Text</div>
</body>
</html>    

Read More: Why you need ASP.NET Core in your tech stack?

Difference between document.ready and window.onload

let's take a look at some of the basic differences between document.ready and window.onload:
$(document).ready()window.onload
$(document).ready() is particularly used for jQuerywindow.onload is an event that a built-in JavaScript.
It only waits for the DOM till it is fully loaded and no other external resources.It waits till the end until all the assets of the page have loaded.
It is faster.It can slower sometimes especially if the loading pages are a bit heavy.
It requires jQuery library to operate.It works very well with all the browsers.
Through this, we can assign and execute many functions in a specific order.We can assign only one function to window.onload.

Introducing Update Panel Partial PostBack with pageLoad() and $(document).ready()

Since we know, in asp.net update panel gets partially postback to the server. Hence If you are using $(document).ready() and pageLoad() methods on the page, it is mandatory to know the difference between both the methods.

pageLoad() methods is called each and every partial postback of update panel but $(document).ready() is not called each and every partial postback of update panel. $(document).ready() is called only one time (during first time of page loading). Hence code written in $(document).ready() method will not be initialized each and every partial postback.

<script type="text/javascript">
 function pageLoad() 
{ 
// code for initialization in each and every partial postback
 } 
$(document).ready(function(){ 
 // code for one time initialization
}); 
</script> 
<asp:ScriptManager ID="ScriptManger1" runat="server" /> 
<asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
<ContentTemplate> 
<!-- Asp.net Controls Here --> 
</ContentTemplate> 
 </asp:UpdatePanel> 

An ASP.NET AJAX alternative to $(document).ready()

If you are using AJAX on your asp.net web page then you can use Application.add_init() method in place of $(document).ready() for one time initialization.

<asp:ScriptManager ID="ScriptManager1" runat="server" /> 
 <script type="text/javascript"> 
 Sys.Application.add_init(function() { 
 // Initialization code here, meant to run once.
 }); 
 </script> 

Note that to call Application.add_init, we need to place it after the ScriptManager. This is required because the ScriptManager injects its reference to MicrosoftAjax.js at that location. Attempting to reference the Sys object before Script Maanager will throw a javascript error "sys is undefined"

Note

  1. $(document).ready()

    1. Best for onetime initialization.

    2. Called as soon as DOM is ready; may called slightly before than pageLoad().

    3. Cross browser compatible.

    4. Unable to re-attach the functionality to elements/controls of the page affected by partial postbacks.

  2. pageLoad()

    1. Not best for onetime initialization if used with UpdatePanel.

    2. Not Cross browser compatible.

    3. Best to re-attach the functionality to elements/controls of the page affected by partial postbacks with UpdatePanel.

  3. Application.Init()

    1. Useful for one time initialization if only ASP.NET AJAX is available.

    2. More work required to wire the event up.

    3. "sys is undefined" javascript error may occurs if you are not careful.

Summary

In this article I try to expose document.ready() and window.onload/pageLoad(). I hope after reading this article you will be able to understand the use of both these methods. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article. To delve deep into core concepts of ASP.NET, consider enrolling in our comprehensive guide ASP.NET Certification Course.

FAQs

Q1. What is the difference between window onload and document ready?

window.onload generally waits for all resources of the page to be loaded completely while document ready does not wait for any external resources, it triggers as soon as the DOM is ready.

Q2. What is the purpose of window onload?

The purpose of window onload run the JavaScript code after all the resources of the page, such as images and stylesheets have been loaded successfully.

Q3. What does document ready mean?

document ready is a jQuery event that is triggered as soon as the DOM hierarchy has been loaded successfully.

Q4. What are the common use cases for document.ready event?

The common use cases for document ready event are execution of JavaScript/jQuery code which manipulates the DOM, binding of event handlers to elements, initializing components just when the DOM hierarchy is loaded successfully.

Take our free aspnet skill challenge to evaluate your skill

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET CHALLENGE

Share Article
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A
  • 10+ Real-world Projects
  • Career Coaching
  • Email Support
Upto 66% OFF
KNOW MORE..

To get full access to all courses

Accept cookies & close this