Does setTimeout solve the DOMContentLoaded problem?

I've recently been building a simple framework for testing the performance of arbitrary JavaScript code. Whilst doing so I was looking at the some information on setTimeout in "JavaScript the Definitive Guide" by David Flanagan.

One paragraph made me think of the DOMContentLoaded Problem:

"In practice, setTimeout() tells the browser to invoke the function when it has finished running the event handlers for any currently pending events and has finished updated the current state of the document"

I thought to myself; what if you apply that to a situation where you don't want to wait for window.onload to fire and use it as a way of emulating DOMContentLoaded.

So I remembered this today and set about creating a noddy little test to see if setTimeout would behave in the way that it sounded like it should do.

I found that setTimeout with a delay of zero milliseconds calls the function without waiting for other resources to finish loading on most modern browsers (IE6/7, firefox and Safari). The only fly in the ointment is Opera. However Opera (Like Mozilla) does have DOMContentLoaded, so it makes sense to use DOMContentLoaded for both Mozilla and Opera.

function DOMReady(f){ 
  if (/(?!.*?compatible|.*?webkit)^mozilla|opera/i.test(navigator.userAgent)){ // Feeling dirty yet?
    document.addEventListener("DOMContentLoaded", f, false);

Try the demo and see what you think.

In Conclusion

setTimeout seems to be another possibility for working around the DOMContentLoaded issues. To be clear however, I'm not saying this is the most bombproof method and it certainly warrants further testing before being considered as a trusted solution.

Any thoughts and suggestions welcome.

Related Reading

comments powered by Disqus