document.ready vs Javascript onload

It is a small post, who are new to jQuery or just started working with jQuery. As we all know that jQuery is Client side library and provides a wrapper over JavaScript . One of the very good things about jQuery that it runs seamlessly in all leading browsers while you must have faced many issues related to the browsers when you work with JavaScript.

So let’s jump to the topic. What is the difference between let’s first go by an example.

I have created a simple default.aspx page in my empty application and added few images and put the path from web and added few text. Now I put a general alert and called it on load method of window as

<script type="text/javascript" language="javascript">
        window.onload = OnLoad();
        function OnLoad() {
            alert('I am called by window.onload');

Now again I tried to change the code to jQuery document.ready function. And used the code as

$(document).ready(function () {
        function OnLoad() {
            alert('I am called by document.ready');

and when I ran it. I got the alert very fast. So what I wanted to point out here that jQuery’s document.ready runs much earlier the JavaScript onload. Why?

document.ready get’s fired as soon as DOM is ready and registered with the browser. It does not wait for the all the resources to get loaded. It allows us some very cool showing, hiding and other effects as soon as user sees the first element on the page.

While Javascript’s onload method gets fired only when all content of the webpage and image, iframes etc get loaded in browser then onload get’s fired.

So do we have a method in JavaScript that works in similar way as document.ready?

Partially yes.

We have a method called DOMContentLoaded  that is actually called by jQuery from document.ready. But that’s not it.  DOMContentLoaded is not available to every browser and versions. For IE > 9,  onreadystatechange works in the same way. In case nothing works in browser, jQuery has a fallback and it implemented own logic to traverse the DOM and check the when the DOM got registered and fires document.ready accordingly.

So I hope you all got to know the basic difference between these two.


Leave a Reply

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

You are commenting using your 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