JavaScript: DOM load events, execution sequence, and $(document).ready()

Javascript is executed as it is seen. Usually, the browser stops parsing the page as soon as it sees a <script> tag, downloads and runs the script, and then keeps going. This is why it’s commonly advised to put <script> tags at the bottom: so the user doesn’t have a blank page while the browser waits for the scripts to download.

However, starting from Firefox 3.5, scripts are downloaded in the background while the rest of the page is rendered. In the now-unusual event that the script uses document.write or similar, Firefox will back up and redraw as necessary. I don’t think other browsers do this at the moment, but I wouldn’t be surprised if it were forthcoming, and IE at least supports a defer attribute in the <script> tag that will defer loading the script until after the page is loaded.

DOMContentLoaded is exactly that: it fires as soon as the DOM is loaded. That is, as soon as the browser has parsed all of the HTML and created a tree of it internally. It does NOT wait for images, CSS, etc. to load. The DOM is all you usually need to run whatever Javascript you want, so it’s nice to not have to wait for other resources. However, I believe only Firefox supports DOMContentLoaded; in other browsers, ready() will just attach an event to regular old onload.

Javascript is guaranteed to run in the order it appears in your HTML, so just make sure your function is defined before you try to attach it to an event.

Leave a Comment