是否可以检测到对DOMContentLoaded
事件的支持?
方法就像 Kangax 的解决方案在这里不起作用,因为DOMContentLoaded
没有作为任何元素的属性公开:Detecting event support without browser sniffing
是否可以检测到对DOMContentLoaded
事件的支持?
方法就像 Kangax 的解决方案在这里不起作用,因为DOMContentLoaded
没有作为任何元素的属性公开:Detecting event support without browser sniffing
只需监听所有三个事件,第一个触发获胜。如果获胜者是 DOMContentLoaded,则支持。如果在触发其他两个之一时尚未触发,则不支持。
<script>
var hasDOMContentLoaded = false,
ready = false,
readyMethod = null;
// Listen for "DOMContentLoaded"
document.addEventListener("DOMContentLoaded", function(event) {
hasDOMContentLoaded = true;
init("DOMContentLoaded");
});
// Listen for "onreadystatechange"
document.onreadystatechange = function () { init("onreadystatechange"); }
// Listen for "load"
document.addEventListener("load", function(event) { init("load"); });
// Gets called after any one of the above is triggered.
function init(method) {
if(!ready) {
ready = true;
readyMethod = method;
go();
}
}
// Page is ready, time is up.
// Eitehr DOMContentLoaded has been triggered or it never will.
function go() {
console.log("hasDOMContentLoaded: ", hasDOMContentLoaded);
// My initialization code here
}
</script>
实际上和事实上,不需要DOMContentLoaded Event。由于 html 流加载的原理,任何脚本都可以用来确定文档 HTML 是否被完全解析。
您所要做的就是将函数(否则将分配给 DOMContentLoaded 事件)放在文档的结束标记之前。
它会在最后一个 HTML 元素被解析为 DOM 之后执行,并且它会比内置的 DOMContentLoaded 执行得更快更早。
I found the following explanation about usage of the DOMContentLoaded event from the mozilla developer site very useful. At the end it talks about backwardly compatible ways to do achieve the same thing, which I have extracted here (no surprise it concentrates on IE)...
Internet Explorer 8 supports the readystatechange event, which can be used to detect when the DOM is ready. In earlier versions of Internet Explorer, this state can be detected by repeatedly trying to execute document.documentElement.doScroll("left");, as this snippet will throw an error until the DOM is ready.