Open In App

Difference between body.onload() and document.ready() function

Last Updated : 01 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The body.onload() event will be called once the DOM and all associated resources like images got loaded. Basically, onload() will be called when the page has been fully loaded with entire images, iframes and stylesheets, etc.

For example, if our page contains a larger size image, so onload() event will wait till the image is fully loaded.
 

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <!-- using jquery library -->
    <script 
    </script>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
     
</head>
  
<body onload="loadBody()">
    <h2>GeeksForGeeks</h2>
  
    <script>
       function loadBody(){
           alert("page loaded");
       }
    </script>
</body>
  
</html>


Output:

body onload

 

The document.ready() function will be executed as soon as the DOM is loaded. It will not wait for the resources like images, scripts, objects, iframes, etc to get loaded.

We can have multiple document.ready() function in our code but only one body.onload() is allowed.

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <!-- Using jquery library -->
    <script src="https://code.jquery.com/jquery-git.js"></script>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
     
</head>
  
<body onload="loadBody()">
    <h2>GeeksForGeeks</h2>
  
    <script>
       $(document).ready(function(){
           alert("ready - page loaded")
       })
    </script>
</body>
  
</html>


Output:

DOM is ready

Difference between body.onload and document.ready:

body.onload() document.ready()
onload() will be called only when everything gets loaded. This function is called as soon as DOM is loaded.
It will wait till all resources like images, iframes, objects, scripts get loaded. It will be called once DOM is loaded.
We can have only one body.onload() function. We can have multiple documents.ready() function in our page.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads