Using setTimeout to Solve DOMContentLoaded?

Written by on February 15th, 2008 in Ajax News.

Stuart Colville was reading the following info on setTimeout() from JavaScript the Definitive Guide:

“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”

He then thought, does setTimeout solve the DOMContentLoaded problem?.

He tested this hypothesis with a simple function that uses DOMContentLoaded for Mozilla and Opera, else uses setTimeout:

JAVASCRIPT:

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

Jonathan Snook ran with this and found that it works until gzip gets into the picture:

If you could guarantee that the file would be sent via gzip compression every time then yes, using setTimeout could potentially be a viable way to mimic DOMContentLoaded. In fact, you could forego using DOMContentLoaded at all and simply rely on setTimeout for all browsers. window.setTimeout could be the new window.onload.

In a related note, I recently saw some benchmarks showing that setTimeout(…, 0) may take longer than you think to run.

Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/235547878/using-settimeout-to-solve-domcontentloaded

Comments are closed.



Site Navigation