Difference Between Document.Ready and Window.Load

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Difference Between Document.Ready and Window.Load

When developing a website you constantly think about the most efficient way to write your code, especially when writing jQuery. For those that have not read my JavaScript vs jQuery article, jQuery is a simplified library of JavaScript to help developers build websites quicker and easier. Typically when starting a jQuery file, programmers would wrap their jQuery code in a $(document).ready(), but is this always the correct way to start your file? The answer is no. You can also start your jQuery document with a $(window).load(). The difference, let me explain.

 

$(document).ready(function(){

//Do code, or continue article

This function can be broken into two parts, document and ready. $(document) is the physical web page which contains all of the rendered code that the user physically sees on their computer monitor. The ready() method tells the web browser (Firefox, Google Chrome, Internet Explorer, etc…) to wait until the document (DOM) or the html has been read before triggering the code inside the function. For example, if this paragraph was a block of code, it would not run until the document was read by the browser because it is inside of a $(document).ready();

});

 

$(window).load(function(){

//Do code, or continue article

Much like the document.ready function, this function can also be broken into two parts, window and load. $(window) is simply an open window in the user’s browser. The load() method tells your browser to wait until the webpage is completely loaded before running the script inside of it. This means that load() waits until html, css, images, videos, audio, essentially all files have finished loading before being triggered. For example, if this paragraph was code, it would wait until the window was completely loaded (the little spinning gif in the top left of the tab stops spinning) before the code would run.

});

 

So there may still be some confusion between the two. Basically to simplify it, ready() waits until all the html on the page has been read, whereas load() doesn’t run until the browser reads the html, knows what files to fetch, fetches the files, renders the files and the loading gif in the top left corner of the tab stops spinning.

Hopefully this will help clear up any confusion between $(document).ready() and $(window).load(). Happy Programming!

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Let’s Get Started!

COVID-19 Message

NetGain remains open during the pandemic.  Our team is working safely from home to help our clients through this unprecedented event.

As digital marketers, we are treating this interruption as a unique opportunity to help our clients stay active online and improve their web presence.  Together, we can transform a challenging situation into limitless opportunity.