Skip to content Skip to sidebar Skip to footer

Document.ready Clarification?

I lately saw some sites which uses this pattern : <

Solution 1:

If you think about all the kinds of resources in a page, many can be loaded separately from the page content: images and stylesheets, for example. They may change the look of the page, but they can't really change the structure, so it's safe to load them separately.

Scripts, on the other hand, have this little thing called document.write that can throw a wrench into the works. If I have some HTML like this:

Who would <script>document.write("<em>");</script>ever</em> write like this?

Then browsers will parse it just fine; document.write, if used at the top level like that, effectively inserts HTML at that position to be parsed. That means that the whole rest of the page depends upon a script element, so the browser can't really move on with the document until that script has loaded.

Because scripts can potentially modify the HTML and change the structure, the browser can't wait to load them later: it has to load them at that moment, and it can't say the DOM is ready yet because a script might modify it. Therefore, the browser must delay the DOM ready event until all the scripts have run. This makes it safe for you to put the dependent code at the top in a ready handler.

However, I'd recommend you don't, because it's not very clear.

Solution 2:

The event that $(document).ready equates to is DOMContentLoaded in modern browsers (and it falls back to some others in legacy browsers that equate to the same scenario).

MDN summarizes it pretty nicely:

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

So your scripts will always be parsed by the time it is executed.

Post a Comment for "Document.ready Clarification?"