It seems that many people are confused about how DOM is loaded and what order it does. I will try to clarify how your scripts are loaded and how it should affect your development.
First thing people need to be aware is where to include their scripts. There is a significant difference between placing your script in your head tag versus including them in your body near the bottom. This what actually happens:
But if you place your script tags near the bottom of your HTML, the browser will get a chance to go through your HTML and start populating your screen with the content until it ever reaches those script files. This is a great plus if you care about improving usability. Your users will start to see what your page looks like instantly
This is how your page should be structured like:
Briefly this is the process your browser goes through:
- Browser will start fetching my Stylesheets
- Move down the HTML. start populating display with HTML.
- Once fetched execute them.
Amazing, already looking good. But this article was about correct use of .ready() and .load() right? Yes, you are right. But where you place your script makes a huge difference and I wanted to clarify that first.
There might be some edge cases where you could be doing some fancy things and your DOM might not be in the status you expect it to be for whatever reason. Then it is acceptable use the .ready() method in that scenario.
.load() method diffirentiates from .ready() where assets could be fetched from the server but has not got a chance to load on the screen yet. This is usually the case for images. They get downloaded but it might take a while to render them on the screen. This is when .load() becomes very useful and you can use it pretty much anywhere in your code to wait for those images to load and do something with it.
Lets see some good and bad examples:
This is a BAD EXAMPLE:
The code above is trying to access a DOM element (the div with the id #content) before it is been populated. Therefore it is going to fail.
Somewhat BAD EXAMPLE”
The code above is actually going to work, but it has unnecessary syntax surrounding it. The div#content element has already been populated and is ready to work on. At this point we don’t need to wait for DOM to be ready anymore.
The Final and the CORRECT EXAMPLE:
The bottom line is you need to know how and when your DOM is loaded to make your life easier.