JavaScript Tip: Waiting for the DOM to Load

As we have started to learn about the DOM this season, one thing that is an issue when developing your scripts is knowing when you can have your scripts execute. Remember, the DOM is available to you only when it has finished loading in the browser. You may ask, when has it finished loading? Good Question!

The order of completion that takes place inside a browser is roughly:

1. HTML is parsed
2. External scripts/style sheets are loaded
3. Scripts are executed as they are parsed in the document
4. DOM is fully constructed
5. Images and external content are loaded
6. The page is finished loading

Scripts that are in the header and loaded from an external file are executed before they DOM is actually constructed. This is a problem because all script executed in those two places won’t have access to the DOM. However, thankfully, there exists a number of workarounds for this problem.

The most common technique is to wait for the entire page to load before performing any DOM operations. Although it is the slowest technique, it is the safest, easiest and works on all browsers. You can do this using a nunber of ways.

One way is to just attach a function to the load event of the page.

Although functional, it is limited because you can only execute one function on the page load since only the last specified function will actually be executed.

You could create an anonymous function to hold the other functions and the last function (the anonymous one) will be executed last which then executes the functions you want:

This works fine, and it’s the simplest solution when you have a small number of functions.

There’s another solution that scales quite nicely, no matter how many functions you want to execute when the page loads. It takes a few more lines to setup initially but, once it’s in place, attaching functions to window.onload is an easy task. This function is called “addLoadEvent” and it was written by Simon Willison.

It takes a single argument: the name of the function that you want to execute when the page loads.

Here’s what addLoadEvent does:

1. Stores the exisiting window.onload as a variable called oldonload
2. If this hasn’t yet had a function attached to it, then simply add the new function in the usal way
3. If there is already a function attached, add the new function after the exisiting instrctions.

This effectively creates a queue of functions to be executed when the page loads. To add functions to this queue you just need to write:

Of course this can easily be replaced with a simple bit of jQuery:

 

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *