浏览器加载页面是按从上到下顺序加载的,如果想要在页面加载完成时被触发脚本,可以监听这两个事件 : load 和 DOMContentLoaded
load
load事件是页面 "loading complete"的标志
window.onload = function (){
//do something
}
缺点
在所有资源完全加载后才被触发,包括图片,会导致比较严重的延迟
因此这个方法很少使用,开发人员又制定了DOMContentLoaded事件
DOMContentLoaded
DOMContentLoaded在DOM加载之后及资源加载之前被触发,不支持IE8及其以下
document.addEventListener( "DOMContentLoaded", ready, false)
Hacks for IE<9
function bindReady(handler){
var called = false
// 确保handler只执行一次
function ready() {
if (called) return
called = true
handler()
}
if ( document.addEventListener ) {
// native event
document.addEventListener( "DOMContentLoaded", ready, false )
} else if ( document.attachEvent ) {
// IE
try {
var isFrame = window.frameElement != null
} catch(e) {}
// IE, the document is not inside a frame
if ( document.documentElement.doScroll && !isFrame ) {
function tryScroll(){
if (called) return
try {
document.documentElement.doScroll("left")
ready()
} catch(e) {
setTimeout(tryScroll, 10)
}
}
tryScroll()
}
// IE, the document is inside a frame
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
ready()
this.onreadystatechange = null
}
})
}
// Old browsers
if ( window.addEventListener ) {
window.addEventListener('load', ready, false)
} else if ( window.attachEvent ) {
window.attachEvent('onload', ready)
} else {
// very old browser, copy old onload
var fn = window.onload
// replace by new onload and call the old one
window.onload = function() {
fn && fn()
ready()
}
}
}
主流框架中DOMContentLoaded事件的实现:
http://www.html5jscss.com/mian_ready.html
网友评论