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

SUMMARY: Run Javascript after the DOM has loaded but before the entire page has fully loaded (for faster loading time) because your code relies on working with the DOM.  This can be done with $( document).ready() in jQuery.

$(document).ready() in jQuery executes when the DOM (Document object model) is loaded on your page. DOM means all the html tags/script. It will not wait for the images, frames to be fully loaded.  It is the earliest stage in page load process and executes a bit earlier than window.onload(), thus less time-consuming for the browser.

window.onload() in JavaScript executes when all the content on your page is fully loaded including the DOM, asynchronous javascript, frames, images, and other assets.

PAGE LOADING STAGES:

  1. Browser makes a request to download the page
  2. Raw markup and DOM is loading (does not include external sources such as images and stylesheets).  DOMContentLoaded event occurs at the end of this stage and you can set your code to run at this time with $(document).ready().
  3. Page is fully loaded with images and stylesheets.  Load event occurs at the end of this stage and you can execute your code to run at this time with window.onload().  (You rarely need to do this unless you need to work with the images or assets in your code).
Advertisements
$(document).ready() vs. window.onload()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s