window.onload vs $(document).ready()

$(document).ready() is a jQuery event. JQuery’s $(document).ready() method gets called as soon as the DOM is ready (which means that the browser has parsed the HTML and built the DOM tree). This allows you to run code as soon as the document is ready to be manipulated.

For example, if a browser supports the DOMContentLoaded event (as many non-IE browsers do), then it will fire on that event. (Note that the DOMContentLoaded event was only added to IE in IE9+.)

Two syntaxes can be used for this:

$( document ).ready(function() {
   console.log( "ready!" );
});

Or the shorthand version:

$(function() {
   console.log( "ready!" );
});

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.

window.onload() is a native JavaScript function. The window.onload() event fires when all the content on your page has loaded, including the DOM (document object model), banner ads and images. Another difference between the two is that, while we can have more than one $(document).ready() function, we can only have one onload function.