Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between (window).load() and (document).ready() functions in jQuery?
Both the methods are used in jQuery. Let's see what purpose they fulfill and understand the key differences between them.
$(document).ready()
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document).ready() method will run once the page DOM is ready to execute JavaScript code, but before all images and other resources are fully loaded.
Example
You can try to run the following code to learn how to use $(document).ready() in jQuery ?
<html>
<head>
<title>jQuery Function</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function() {
alert("Hi!");
});
});
</script>
</head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div>
</body>
</html>
$(window).load()
The code which gets included inside $(window).on("load", function() { ... }) runs only once the entire page is ready, including all content such as images, frames, objects, and stylesheets (not only DOM).
Note: The load() method was deprecated in jQuery version 1.8 and completely removed in version 3.0. To see its working, you need to use jQuery version before 3.0.
Example
You can try to run the following code to learn how to use $(window).load() in jQuery ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(window).load(function(){
alert("Page and all resources fully loaded!");
});
$(document).ready(function(){
$("img").load(function(){
alert("Image successfully loaded.");
});
});
</script>
</head>
<body>
<img src="/videotutorials/images/tutor_connect_home.jpg" alt="Tutor Connect" width="310" height="220">
<p><strong>Note:</strong> The load() method was deprecated in jQuery version 1.8 and completely removed in version 3.0.</p>
</body>
</html>
Key Differences
The main difference is timing: $(document).ready() executes when the DOM is fully constructed, while $(window).load() waits for all page resources to finish loading. Use $(document).ready() for most DOM manipulation tasks, and $(window).load() when you need to ensure images and other resources are completely loaded.
Conclusion
Choose $(document).ready() for faster execution when working with DOM elements, and $(window).load() when you need all page resources fully loaded before executing your code.
