DOM.ensure a DOMReady approach
September 27th, 2007
DOM.ensure( function(){
$("node").observe("click",method1);
});
If we decide that we want to cache that markup and reinsert it back into the DOM later we’re still safe. If we had used the DOMReady approach our code would have needed to be much more complex to track when it’s ok to call the method and when it needs to be called in the event. This method is really away of letting us say we want to ensure that this block of code is not executed until the DOM is really ready.
Here’s a solution I created for implementing DOM.ensure.
DOM = Class.create();
Object.extend(DOM,{
callQueue: $A([]), // store all calls in this queue
isReady: false,
// make sure the DOM may be effected before calling this method
// if the DOM is ready then the method is called right away, else a timeout is set
// until the DOM is ready
ensureDOMIsReady: function(callback)
{
if( DOM.isReady ){
callback(); // call the method now
}
else{ // delay the call until the DOM is ready
DOM.callQueue.push( callback );
}
},
initialize: function() // call any methods that were queued up to be run when the DOM is ready
{
DOM.isReady = true;
var queue = DOM.callQueue;
while( queue.length > 0 ){
queue.pop()();
}
}
});
// detect DOM ready once for the whole page for each specific browser type
if( Prototype.Browser.IE ){
document.onreadystatechange = function(){
if( document.readyState == "complete" ){
DOM.initialize();
}
}
}
else if( Prototype.Browser.WebKit ){// safari 2.0
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(_timer);
DOM.initialize();
}
}, 10);
}
else if( document.addEventListener ){
document.addEventListener("DOMContentLoaded", DOM.initialize.bind(this), false);
}
Really it’s a change in the calling semantics for a DOMReady to think of it as more of a question of whether or not the DOM is ready for me to manipulate it.

You really need to have a look at lowpro.js.
lowpro.js