onload触发时机:文档和所有的图片都加载完毕
DOMContentLoaded触发时机:文档加载并解析完毕,所有deferred脚本执行完毕。但此时图片和async脚本可能依旧在加载。
readystatechange触发时机:
document.readyState属性包含多个状态,当值为“complete”时表明文档加载并执行完毕。
将事件绑定到DOMReady上的方法封装:
var whenReady = ( function(){ var funcs = []; var ready = false; function handler( e ){ if( ready ) return; if( e.type === "readystatechange" && document.readyState !== "complete" ) return; for( var i=0; i < funcs.length; i++ ){ funcs[i].call( document ); } ready = true; funcs = null; } if( document.addEventListener ){ document.addEventListener( "DOMContentLoaded", handler, false ); document.addEventListener( "readystatechange", handler, false ); window.addEventListener( "load", handler, false ); }else if( document.attachEvent ){ document.attachEvent( "onreadystatechange", handler ); window.attachEvent( "load", handler ); } return function whenReady( f ){ if( ready ) f.call( document ); else funcs.push( f ); } }() );