我想检测<body>
元素何时从外部脚本加载到DOM而不使用外部JavaScript库。我不想使用document.ready
或window.onload
因为它们在整个DOM(包括所有外部文件)完成加载之前不会触发。
答案 0 :(得分:0)
对于现代浏览器,请使用
window.addEventListener('DOMContentLoaded', function() {
// dom is ready
}, false);
对于IE8使用
window.onload = function() {
// dom is ready
};
答案 1 :(得分:0)
为什么不把脚本放在关闭正文标记
的正上方<body>
..
....
....
<script type="text/javascript".....
</script>
</body>
确保所有内容都已加载
回应评论
将此代码放在文档的头部
对于IE8和较旧的IE
window.onload= function() {
var script=document.createElement("script");
script.src=url; // here use the url of the script
document.body.appendChild(script);
};
为他人
window.attachEventListener("DOMContentLoaded",function() {
var script=document.createElement("script");
script.src=url; // here use the url of the script
document.body.appendChild(script);
},false);
答案 2 :(得分:0)
这是一个适用于所有浏览器的简单解决方案:
在HTML中的</body>
标记上方插入以下代码:
<script type="text/javascript">
try {
ONLOAD()
} catch(e) {
ONLOADq=1
}
</script>
MINIFIED:
<script type="text/javascript">try{ONLOAD()}catch(e){ONLOADq=1}</script>
将此代码插入外部javascript:
if ( typeof ONLOADq === 'number') {
ONLOAD()
};
将需要在页面加载时运行的外部javscript中的所有代码放入名为ONLOAD
的函数中。例如:
function ONLOAD() { document.body.appendChild(ST1) };
第一部分包括外部javascript在HTML之前加载的实例,第二部分包括第二部分,反之亦然。