1. 程式人生 > >dom載入完的判斷

dom載入完的判斷

window.onload事件可以安全的執行javascript,因為該事件是在頁面完全載入完後才開始執行(包括頁面內的圖片、flash等所有元素),不會因為JS需要對某個DOM 操作,而頁面還沒有載入該節點而引起錯誤。但是這種安全是需要付出代價的:如果某些圖片(或者一些別的東西)載入特別慢,那麼load事件會等到很久之後才會觸發。針對這個問題,一些JS框架提供了一些補充方法。如:jquery的$(document).ready()、mootools的domready事件。都是在頁面的DOM載入完畢後立即執行,而不需要等待漫長的圖片下載過程。如果不使用這些框架,可以使用這個獨立的DomReady.js

小巧獨立的Javascript庫:DomReady.js

(function(){

    var DomReady = window.DomReady = {};

	// Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery. 

    var userAgent = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used
    var browser = {
    	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
    	safari: /webkit/.test(userAgent),
    	opera: /opera/.test(userAgent),
    	msie: (/msie/.test(userAgent)) && (!/opera/.test( userAgent )),
    	mozilla: (/mozilla/.test(userAgent)) && (!/(compatible|webkit)/.test(userAgent))
    };    

	var readyBound = false;	
	var isReady = false;
	var readyList = [];

	// Handle when the DOM is ready
	function domReady() {
		// Make sure that the DOM is not already loaded
		if(!isReady) {
			// Remember that the DOM is ready
			isReady = true;
        
	        if(readyList) {
	            for(var fn = 0; fn < readyList.length; fn++) {
	                readyList[fn].call(window, []);
	            }
            
	            readyList = [];
	        }
		}
	};

	// From Simon Willison. A safe way to fire onload w/o screwing up everyone else.
	function addLoadEvent(func) {
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
	    window.onload = func;
	  } else {
	    window.onload = function() {
	      if (oldonload) {
	        oldonload();
	      }
	      func();
	    }
	  }
	};

	// does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.
	function bindReady() {
		if(readyBound) {
		    return;
	    }
	
		readyBound = true;

		// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
		if (document.addEventListener && !browser.opera) {
			// Use the handy event callback
			document.addEventListener("DOMContentLoaded", domReady, false);
		}

		// If IE is used and is not in a frame
		// Continually check to see if the document is ready
		if (browser.msie && window == top) (function(){
			if (isReady) return;
			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll("left");
			} catch(error) {
				setTimeout(arguments.callee, 0);
				return;
			}
			// and execute any waiting functions
		    domReady();
		})();

		if(browser.opera) {
			document.addEventListener( "DOMContentLoaded", function () {
				if (isReady) return;
				for (var i = 0; i < document.styleSheets.length; i++)
					if (document.styleSheets[i].disabled) {
						setTimeout( arguments.callee, 0 );
						return;
					}
				// and execute any waiting functions
	            domReady();
			}, false);
		}

		if(browser.safari) {
		    var numStyles;
			(function(){
				if (isReady) return;
				if (document.readyState != "loaded" && document.readyState != "complete") {
					setTimeout( arguments.callee, 0 );
					return;
				}
				if (numStyles === undefined) {
	                var links = document.getElementsByTagName("link");
	                for (var i=0; i < links.length; i++) {
	                	if(links[i].getAttribute('rel') == 'stylesheet') {
	                	    numStyles++;
	                	}
	                }
	                var styles = document.getElementsByTagName("style");
	                numStyles += styles.length;
				}
				if (document.styleSheets.length != numStyles) {
					setTimeout( arguments.callee, 0 );
					return;
				}
			
				// and execute any waiting functions
				domReady();
			})();
		}

		// A fallback to window.onload, that will always work
	    addLoadEvent(domReady);
	};

	// This is the public function that people can use to hook up ready.
	DomReady.ready = function(fn, args) {
		// Attach the listeners
		bindReady();
    
		// If the DOM is already ready
		if (isReady) {
			// Execute the function immediately
			fn.call(window, []);
	    } else {
			// Add the function to the wait list
	        readyList.push( function() { return fn.call(window, []); } );
	    }
	};
    
	bindReady();
	
})();

 

使用方法:

<html lang="en"> 
<head> 
    <script src="domready.js" type="application/javascript"></script> 
    <script type="application/javascript"> 
        DomReady.ready(function() { 
            alert('dom is ready'); 
        }); 
    </script> 
</head> 
<body> 
</body> 
</html> 

 

 

 

     jquery裡有專門解決DOM載入的函式$(document).ready()(簡寫就是$(fn)),非常好用!John Resig在《Pro JavaScript Techniques》裡,有這樣一個方法處理DOM載入,原理就是通過document&& document.getElementsByTagName &&document.getElementById&& document.body 去判斷Dom樹是否載入完畢。程式碼如下:

function domReady( f ) {
// 如果DOM載入完畢,馬上執行函式
if ( domReady.done ) return f();   
// 假如我們已增加一個函式
if ( domReady.timer ) { 
// 把它加入待執行的函式清單中
domReady.ready.push( f ); 
} else { 
// 為頁面載入完成繫結一個事件, 
// 為防止它最先完成. 使用 addEvent(下面列出).
addEvent( window, “load”, isDOMReady );   
// 初始化待執行的函式的陣列
domReady.ready = [ f ];   
// 經可能快地檢查Dom是否已可用
domReady.timer = setInterval( isDOMReady, 13 ); 

}  
// 檢查Dom是否已可操作
function isDOMReady() { 
// 假如已檢查出Dom已可用, 忽略 
if ( domReady.done ) return false;   
// 檢查若干函式和元素是否可用
if ( document &&  document.getElementsByTagName &&  document.getElementById &&  document.body ) {   
// 假如可用, 停止檢查
clearInterval( domReady.timer ); 
domReady.timer = null;   
// 執行所有等待的函式
for ( var i = 0; i < domReady.ready.length; i++ ) 
domReady.ready[i]();   
// 記錄在此已經完成
domReady.ready = null; 
domReady.done = true; 

}
// 由 Dean Edwards 在2005 所編寫addEvent/removeEvent,
// 由 Tino Zijdel整理
// http://dean.edwards.name/weblog/2005/10/add-event/
//優點是1.可以在所有瀏覽器工作;
//2.this指向當前元素;
//3.綜合了所有瀏覽器防止預設行為和阻止事件冒泡的的函式
//缺點就是僅在冒泡階段工作
function addEvent(element, type, handler) {
    // assign each event handler a unique ID
    if (!handler.$$guid) handler.$$guid = addEvent.guid++;
    // create a hash table of event types for the element
    if (!element.events) element.events = {};
    // create a hash table of event handlers for each element/event pair
    var handlers = element.events[type];
    if (!handlers) {
        handlers = element.events[type] = {};
        // store the existing event handler (if there is one)
        if (element["on" + type]) {
            handlers[0] = element["on" + type];
        }
    }
    // store the event handler in the hash table
    handlers[handler.$$guid] = handler;
    // assign a global event handler to do all the work
    element["on" + type] = handleEvent;
};
// a counter used to create unique IDs
addEvent.guid = 1;
function removeEvent(element, type, handler) {
    // delete the event handler from the hash table
    if (element.events && element.events[type]) {
        delete element.events[type][handler.$$guid];
    }
};
function handleEvent(event) {
    var returnValue = true;
    // grab the event object (IE uses a global event object)
    event = event || fixEvent(window.event);
    // get a reference to the hash table of event handlers
    var handlers = this.events[event.type];
    // execute each event handler
    for (var i in handlers) {
        this.$$handleEvent = handlers[i];
        if (this.$$handleEvent(event) === false) {
            returnValue = false;
        }
    }
    return returnValue;
};
function fixEvent(event) {
    // add W3C standard event methods
    event.preventDefault = fixEvent.preventDefault;
    event.stopPropagation = fixEvent.stopPropagation;
    return event;
};
fixEvent.preventDefault = function() {
    this.returnValue = false;
};
fixEvent.stopPropagation = function() {
    this.cancelBubble = true;
};

還有一個估計由幾個外國大師合作寫的,實現同樣功能。

/*
* (c)2006 Jesse Skinner/Dean Edwards/Matthias Miller/John Resig
* Special thanks to Dan Webb's domready.js Prototype extension
* and Simon Willison's addLoadEvent
*
* For more info, see:
* http://www.thefutureoftheweb.com/blog/adddomloadevent
* http://dean.edwards.name/weblog/2006/06/again/
* http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype
* http://simon.incutio.com/archive/2004/05/26/addLoadEvent

*
* To use: call addDOMLoadEvent one or more times with functions, ie:
*
*    function something() {
*       // do something
*    }
*    addDOMLoadEvent(something);
*
*    addDOMLoadEvent(function() {
*        // do other stuff
*    });
*
*/
addDOMLoadEvent = (function(){
    // create event function stack
    var load_events = [],
        load_timer,
        script,
        done,
        exec,
        old_onload,
        init = function () {
            done = true;
            // kill the timer
            clearInterval(load_timer);
            // execute each function in the stack in the order they were added
            while (exec = load_events.shift())
                exec();
            if (script) script.onreadystatechange = '';
        };
    return function (func) {
        // if the init function was already ran, just run this function now and stop
        if (done) return func();
        if (!load_events[0]) {
            // for Mozilla/Opera9
            if (document.addEventListener)
                document.addEventListener("DOMContentLoaded", init, false);
            // for Internet Explorer
            /*@cc_on @*/
            /*@if (@_win32)
                document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
                script = document.getElementById("__ie_onload");
                script.onreadystatechange = function() {
                    if (this.readyState == "complete")
                        init(); // call the onload handler
                };
            /*@end @*/
            // for Safari
            if (/WebKit/i.test(navigator.userAgent)) { // sniff
                load_timer = setInterval(function() {
                    if (/loaded|complete/.test(document.readyState))
                        init(); // call the onload handler
                }, 10);
            }
            // for other browsers set the window.onload, but also execute the old window.onload
            old_onload = window.onload;
            window.onload = function() {
                init();
                if (old_onload) old_onload();
            };
        }
        load_events.push(func);
    }
})();