javascript判断dom是否加载完毕
首先要明确两个概念 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 (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |