When can you query the DOM?

There’s also been discussion in the blogosphere about window.onload, DOMContentLoaded, and defer. In short, the window.onload event fires after all of the page’s content has been loaded: DOM, images and all. But what if you want to execute your script when just the DOM loads, without waiting for everything else?

Yahoo! (well, Dean Edwards did first with their latest YUI release.

What’s the best way to do this? Well, I’ve been handling this on a case-by-case basis.

  • Can my script wait until window.onload fires? If it can, then I’ll use that. Why? There’s no need for the extra overhead of polling when I can wait for the window.onload hook. (Now, I’ll probably use YUI’s onContentReady
  • Do I need to work with an element as soon as it’s in the DOM? I had been handling this by placing a >script< block directly after the element in my markup. It works, but it’s not as clean as YUI’s onAvailable method, which I’ve been using more and more often as I’ve gotten further into using the YUI library. In this case, polling the DOM makes sense and my markup remains a little cleaner.

Encapsulating these events with a library may not seem like the most intuitive thing to do (after all, most of the things these libraries encapsualte are one-liners or quick functions that are fairly easy to write). However, a library like YUI brings you more options than the code you write yourself, and, ultimately, those options lead to cleaner, quicker, more responsive code.

technorati tags:, , ,

Comments are closed.

I'm Reading…
Search This Site

AddThis Feed Button

Need great hosting?

Categories