javascript tutorial - [Solved-5 Solutions] window.onload vs $(document).ready() - javascript - java script - javascript array


What are the differences between JavaScript's window.onload and jQuery's $(document).ready()method ?

Solution 1:

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded. The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

Solution 2:

$(document).ready (note that it's not document.ready, which is undefined) is a jQuery function, wrapping and providing consistency to the following events:

  • document.ondomcontentready / document.ondomcontentloaded - a newish event which fires when the document's DOM is loaded (which may be some time before the images, etc. are loaded); again, slightly different in Internet Explorer and in rest of the world
  • and window.onload (which is implemented even in old browsers), which fires when the entire page loads (images, styles, etc.)

Solution 3:

$( document ).ready(function() {
   console.log( "ready!" );
click below button to copy the code. By JavaScript tutorial team

Or the shorthand version:

$(function() {
   console.log( "ready!" );
click below button to copy the code. By JavaScript tutorial team

Main points for $(document).ready():

  • It will not wait for the images to be loaded.
  • Used to execute JavaScript when the DOM is completely loaded. Put event handlers here.
  • Can be used multiple times.
  • Replace $ with jQuery when you receive "$ is not defined."
  • Not used if you want to manipulate images. Use $(window).load() instead.

Solution 4:

window.onload = function(){} and <body onload="func();"> are different ways of using the same event.

Solution 5:

$(document).on('ready', handler) binds to the ready event from jQuery. The handler is called when the DOM is loaded. Assets like images maybe still are missing. It will never be called if the document is ready at the time of binding. jQuery uses the DOMContentLoaded-Event for that, emulating it if not available. $(document).on('load', handler) is an event that will be fired once all resources are loadedfrom the server. Images are loaded now. While onload is a raw HTML event, ready is built by jQuery.

Related Searches to javascript tutorial - window.onload vs $(document).ready()