国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > jscript > javascript判断dom是否加载完毕

javascript判断dom是否加载完毕

来源:程序员人生   发布时间:2013-10-13 03:33:58 阅读次数:4005次

首先要明确两个概念

1.window.onload:页面加载完毕,页面内所有组件(图片等)都可用。

2.dom 加载:指文档对象模型加载完毕,要先于window.onload事件。

可以看出,当页面包含大量组件(特别是图片)的情形下,以上两种加载的时间相隔将会很长,这时判断dom何时加载完成就显得特别重要

页面的一些组件(css,image,flash)不会导致页面的DOM未构建完成。只有JS会阻塞页面的DOM节点的构建

function init() {

// 如果该函数被调用多次,直接返回

if (arguments.callee.done) return;

//

arguments.callee.done = true;

// 清除对safari设置的定时器

if (_timer) clearInterval(_timer);

alert(document.getElementById(“test”).id);

};

// firefox和opera9.0

if (document.addEventListener) {

document.addEventListener(“DOMContentLoaded”, init, false);

}

//ie

document.write(“<script id=__ie_onload defer src=javascript:void(0)></script>”);

var script = document.getElementById(“__ie_onload”);

script.onreadystatechange = function() {

if (this.readyState == “complete”) {

init(); // call the onload handler

}

};

//Safari

if (/WebKit/i.test(navigator.userAgent)) { // sniff

var _timer = setInterval(function() {

if (/loaded|complete/.test(document.readyState)) {

init(); // call the onload handler

}

}, 10);

}

//其它浏览器直接用window.onload事件

window.onload = init;

来源:http://www.wellpeter.com/?p=162

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生