:::: MENU ::::

Difference between jQuery ‘$(document).ready()’ and ‘$(window).load()’ function & usage

This post lead me to write, when i was using the jQuery ‘$(document).ready()’ function & struck with the issue. I was adding the css class.

To know the difference, it’s important to understand the three things:

1. $(document).ready()
Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

<script type="text/javascript" language="javascript">
 $(document).ready(function() {
    //All the code written here will execute, when the DOM is ready 

2.What is DOM?
DOM stands for Document Object Model, It defines the logical structure of documents and the way a document is accessed and manipulated. It is based on an object structure that closely resembles the structure of the documents it models. For instance, consider this table, taken from an HTML document:

      <td>Shady Grove</td>
      <td>Over the River, Charlie</td>

In the above example, the root node is table. The table node has two child nodes; tr and td.

DOM is the logical structure which is very much like a tree; to be more precise, which is like a “forest” or “grove”, which can contain more than one tree.

3. $(window).load()

<script type="text/javascript" language="javascript">
  $(window).load(function() {
     //All the code written here will execute, when complete page loaded  });

The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself.

Sometimes if you want to manipulate pictures. For example you want to vertically and horizontally align a picture and you need to get the width and height of the picture in order to do that. With $(document).ready() you won’t be able to do that if the visitor doesn’t have the image already loaded, in this case window.load can initialize the jquery alignment function when the image finishes loading.

So, what do you think ?