Walter Rumsby's Web Site

On DOM Ready

25 Jun 2008 at 12:00

YUI provides the YAHOO.util.Event.onDOMReady method which "lets you define a function that will execute as soon as the DOM is in a usable state."

I've heard reports (both internally and on the YUI mailing list) about this method going a bit haywire - specifically firing before the DOM is usable - in Internet Explorer, but these seem to be in weird situations and it has been (seemingly) impossible to create a test case to demonstrate when/where/why this problem happens. This makes it pretty difficult to raise a bug that the YUI team can look at, so the problem still (apparently) exists.

I was looking at an old post by Dean Edwards that suggests using the script element's defer attribute to work out when the DOM is "usable" in IE. Edward's solution suggests using conditional comments to remove the defer attribute for non-IE browsers, but I wonder if that's even necessary.

This leads me to think, assuming your external script is entirely wrapped up in an onDOMReady function, why not throw a defer attribute onto the script element? My hunch is:

  • IE will defer the script's execution until the DOM is usable.
  • Other browsers will ignore the defer attribute, but since onDOMReady works for those browsers (assuming they are A Grade browsers) they will also wait until the DOM is usable.
  • By the time IE trys to work out if it should fire onDOMReady the defer attribute will mean that it's okay for it to fire, so you should sidestep the "onDOMReady fires in IE before the DOM is usable" issue.
  • All of this will happen before the window's load event fires regardless of browser.

I've set up an example page which appears to confirm this, but of course this page doesn't suffer from the incredibly tricky to replicate problem so this is very much a guess at a solution. The other thing is this assumes that all the code in your script runs inside an onDOMReady function, which might not be what you want.

I've followed this up with a message on the YUI mailing list to see if anyone can spot any problems with this approach and plan to update this post with anything that comes out of that.

Update: there is now a bug with test cases. Hopefully this is resolved in the next YUI release, but in the interim, or if you are using an older YUI release, it appears that adding the defer attribute to script elements does avoid these errors.

blog comments powered by Disqus