jQuery : Difference Between jQuery Document.Ready() & $(window).on(‘load’ events

$(document).ready() : This event is triggered when the DOM (Document Object Model) is ready, it means that HTML structure of the page has been parsed and is ready to be manipulated with JavaScript. It occurs before all the external resources (like images and stylesheets) are fully loaded.
This event used for tasks that involves DOM manipulation or interaction with DOM elements, such as attaching event handlers, modifying the page content, or initializing plugins. It is good choice when you need to work with the structure of the page but don’t necessarily need to wait for images and other assets to load.

Syntax :

$(document).ready(function() {
  // Place code here
  console.log('Hi, Welcome in webdeveloperindia.in document ready event');
});
// Shorten syntax
$(function() {
  // Place code here
  console.log('Hi, Welcome in webdeveloperindia.in  document ready event shorten');
});

Example :


<!DOCTYPE html>
<html>
<head>
<title>Welcome to webdeveloperindia.in  </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
  // Place code here
  console.log('Hi, Welcome in webdeveloperindia.in');
});
// Shorten syntax
$(function() {
  // Place code here
  console.log('Hi, Welcome in webdeveloperindia.in Shorten code');
});
</script>
</head>
<body>
	<h3>Welcome in webdeveloperindia.in</h3>
</body>
</html>

$(window).on(‘load’, function(){ : This event is triggered after the entire page, including all external resources like images, stylesheets, scripts, etc. has been finished loading.
This event used when you need to ensure that all the resources on the page including images,css are fully loaded before executing JavaScript. It is often used for tasks like calculating dimensions of images or performing actions that depend on the sizes of images or other external assets.

Syntax :

$(window).on('load', function(){
  // Place code here
  console.log('Hi, Welcome in webdeveloperindia.in');
});

Example :


<!DOCTYPE html>
<html>
<head>
<title>Welcome to webdeveloperindia.in</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(window).on('load', function(){
  // Place code here
  console.log('Hi, Welcome in webdeveloperindia.in on load event');
});
</script>
</head>
<body>
	<h3>Welcome in webdeveloperindia.in</h3>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

49 + = 54