One of the common requirements while working with web applications is to execute some script as soon as the web page loads.
As the javascript or jQuery executes on the browser so we have to ensure that the document or the web page is loaded by the browser before the script can be executed.Two common ways to perform this check is by using the window.onload event handler method and the $(document).ready() method.
Javascript provides us the window.onload event to execute the script once the document is fully loaded.This event is specific to javascript.While working with jQuery we have another option to attach the startup script.We can use the $(document).ready() method to execute the script once the Document Object Model or DOM is loaded.
$(document).ready(function() { alert('DOM is loaded'); });
Shorthand for the $( document ).ready() is $() so we can write the above code as:
$(function(){ alert('DOM is loaded'); });
We use the onload event handler as:
<script> function pageLoaded() { alert("Page loaded!"); } </script> <body onload="pageLoaded()"> ... </body>
One important point to note about the $( document ).ready() method is that if we are accessing images inside the $( document ).ready() method then that code could get failed if the images are not yet loaded by the web page.
jQuery’s document ready and the window onload are use for similar requirement but have few important differences.Understanding these differences is important if we are using scripts.
Following are the main differences between $(document).ready() and window.onload event
- One of the main differences is that ready() method will execute once the DOM is loaded but before the other page assets ,such as images are loaded.So ready() will fire at an early stage in the web page loading process than the window.onload event.
- $(document).ready() can significantly improve the performance of the web page if we are heavily using the images on the page or if the network connection is slow.
- We can have only one onload event handler method while we can have multiple document ready methods in a page.
- We can use the $(document).ready() event handler method as many times as we require on the web page.This can help us to keep the code segregated.Having multiple document ready methods can be a good option if the html page is generated by merging dynamically generated server code and the static html.In this case both the parts of the html can define the $(document).ready() methods.
Leave a Reply