DOM构造完成后,立即执行JS的函数(源于jquery)

如果使用onload的话,必须等到整个页面完成后才执行。。图片之类的下载完成后才会执行onload时间,但多数情况下,我们只是操作DOM而已,所以DOM构造完成就可以执行我们的js了,而DOM构造完成不同浏览器的实现都不一样,这个函数兼容多数浏览器,原理可以看...http://peter.michaux.ca/article/553

以下是代码:主要来自于jQuery
function ready(f){
	ready.bindReady();

	if (ready.isReady) {
		f();
	}
	else {
		ready.readyList.push(f);
	}
}

ready.isReady = false;
ready.readyBound = false;
ready.readyList = new Array();
ready.userAgent = navigator.userAgent.toLowerCase();
ready.browser = {
	version: (ready.userAgent.match(/.+(?:rv|it|ra|ie)[/: ]([d.]+)/) || [])[1],
	safari: /webkit/.test(ready.userAgent),
	opera: /opera/.test(ready.userAgent),
	msie: /msie/.test(ready.userAgent) && !/opera/.test(ready.userAgent),
	mozilla: /mozilla/.test(ready.userAgent) && !/(compatible|webkit)/.test(ready.userAgent)
};

ready.execute = function(){
	if (ready.isReady) {
		return;
	}
	var len = ready.readyList.length;
	for (var n = 0; n < len; n++) {
		ready.readyList[n]();
	}

	ready.readyList = null;

	if (ready.browser.mozilla || ready.browser.opera)
	document.removeEventListener("DOMContentLoaded", ready.execute, false);

	ready.isReady = true;
}

ready.bindReady = function(){
	if (ready.readyBound) {
		return;
	}
	ready.readyBound = true;

	if (ready.browser.mozilla || ready.browser.opera) {
		document.addEventListener("DOMContentLoaded", ready.execute, false);
	} else if (ready.browser.msie) {
		document.write("<scr" + "ipt id=__ie_init defer=true " + "src=\/\/:><\/script>");

		var script = document.getElementById("__ie_init");

		if (script) {
			script.onreadystatechange = function(){
				if (this.readyState != "complete")
				return;
				ready.execute();
			};

			script = null;
		}
	} else if (ready.browser.safari) {
		ready.safariTimer = setInterval(function(){
			if (document.readyState == "loaded" ||
			document.readyState == "complete") {

				clearInterval(ready.safariTimer);
				ready.safariTimer = null;

				ready.execute();
			}
		}, 10);
	}

	if (typeof window.addEventListener == "function") {
		window.addEventListener("load", ready.execute, false);
	}
	else if (typeof window.attacheEvent == "function") {
		window.attacheEvent("onload", ready.execute);
	}
}



使用方法
ready(function(){
                alert('DOM构造完成');
            });

你可能感兴趣的:(jquery,Opera,IE,webkit,Safari)