Saturday, May 09, 2009

Why YAHOO.util.Event.onContentReady is better than document.observe('dom:loaded')

I am doing a lot of heavy AJAX stuff in a project I am working on. I really like prototype, and was using document.observe('dom:loaded') to bootstrap my javascript. Using this method prevents the "operation aborted" error in IE and allows you to defer javascript processing until the DOM is fully loaded, making your web page seem load a bit faster for the user as well.

In this current project, I am loading up a web page in a DHTML dialog using a custom subclass of YUI's Dialog object. The sub-page I'm loading includes the document.observe('dom:loaded') bootstrapping code. Since this all happens on-page via AJAX, the dom:loaded event never gets called for the sub-page, so the sub-page never gets its Javascript bootstrapped!

YUI's YAHOO.util.Event.onContentReady is just like dom:loaded, but much more flexible. It can be called at any time (before or after the DOM is Ready) and will either fire immediately, or later on, once your requested content is detected. It does this by periodically scanning the DOM for your element for some # of seconds after being called.

In this case, it's a simple swap-out from document.observe('dom:loaded') to YAHOO.util.Event.onContentReady() and the problem is solved!

If you are doing absurd on-page AJAX and loading up other HTML+JS content in your app this technique could be a real life-saver.