Example of Improved Behaviour.addLoadEvent

If you are using MSIE or a Gecko-based browser, the functionality associated with the following button (via Behaviour) should be executed when clicked and before before the image below loads:

Modified code for Behaviour.addLoadEvent

var Behaviour = (
...
addLoadEvent : function(func){
	//Enable application of Behaviours when just the DOM is loaded 
	//  (by Weston Ruter <http://linguiste.org>).
	//   See Dean Edwards's blog: http://dean.edwards.name/weblog/2005/09/busted/
	//Only Gecko supports DOMContentLoaded
	if(document.addEventListener && navigator.userAgent.indexOf('Gecko/') != -1){
		document.addEventListener("DOMContentLoaded", function(){func()}, false);
	}
	//Only MSIE defers execution of scripts until DOM loaded
	else if(/MSIE/.test(navigator.userAgent) && !window.opera){
		var name = Math.random();
		window[name] = function(){func()};

		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = "javascript:window[" + name + "](); " + 
			"window[" + name + "] = null; void(0);";
		script.defer = true;
		document.getElementsByTagName('head')[0].appendChild(script);			
	}
	//fall back to using onload (original Behaviour code)
	else {
		var oldonload = window.onload;
		
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

See also


Weston Ruter, 2006-06-02