Tuesday, February 2, 2016

Difference between $(window).load and $(document).ready

$(document).ready is a jQuery event. It fires as soon as the DOM is loaded and ready to be manipulated by script. This is the earliest point in the page load process where the script can safely access elements in the page's html DOM. This event is fired before all the images, css etc.. are fully loaded.


$(window).load event fires when the DOM and all the content on the page (images, css etc) is fully loaded. This event is fired after all the images, css etc.. are fully loaded that means after ready event.


The following example proves the above point. When you run the page with the following script, notice that the alert in ready function is displayed before the alert in load function.


<script type="text/javascript">
    $(window).load(function () {
        alert('Window loaded');
    });

    $(document).ready(function () {
        alert('DOM Loaded and ready');
    });
</script>

In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. So ready() is usually the best place to write your JavaScript code.

However, in your application there could be scenarios where you should be using $(window).load over $(document).ready. For example, let's say we want to display the actual image dimensions (Height and Width). To get the actual image dimensions, we will have to wait until the image is fully loaded, so the jQuery code to get the height and width should be in $(window).load event.

No comments:

Post a Comment