Cross-browser onDOMContentLoaded

Posted by Tim Sat, 24 Sep 2005 23:08:00 GMT

An elegant solution to the window.onload problem in Mozilla and IE.

Client-side developers have long been frustrated by the shortcomings of window.onload, namely that it takes too long before firing if you want to attach scripts to rework the DOM, yet you have to wait before the DOM is parsed before manipulating it.

The Greasemonkey chaps solved the problem in Mozilla Firefox by uncovering the proprietary DOMContentLoaded event. Now not solving the problem in all browsers would be acceptable, since the other browsers could fall-back to the late firing window.onload, but it’s unrealistic to consider a solution for general web use that doesn’t at least take care of 90% of the market (Windows IE).

Ever since the PPK mentioned something in his blog about a way to solve it in IE and Mozilla(maybe Safari) in the @media event entries a number of us have been very excited. We’ve been contemplating the best way to use this knowledge involving complicated schemes requiring behaviors in IE (.htc files) and waiting for the mysterious “more details to come”

Well, the details have arrived, and it seems to make most of the scripts to handle an early firing domloaded event moot. Dean Edwards has delivered an elegant solution to the window.onload problem in Mozilla and IE. If Safari/kthml, Opera, or any of the other browsers not covered by this are an important enough factor at your site, you might have to still think about an alternative like brothercake’s domFunction.

We’re going to just stick with Dean Edwards solution for now and call it good, though. Especially since, according to work done on the sIFR image replacement technique, Safari won’t layout the page properly until the images are loaded (read the 3rd comment). This means having Safari wait for the window.onload is actually a feature.

Posted in  | 1 comment

Comments

  1. Tim Connor said about 24 hours later:

    He also added a method to handle IE the other way that has been discussed, using an HTC and ondocumentready, in case anyone has any problems with the “defer” approach.

Comments are disabled