我做了一个简单的测试页面:
<!DOCTYPE html>
<html>
<head>
<script>
//
console.log("script run");
//
document.addEventListener('DOMContentLoaded', function(event) {
//
alert("DOMContentLoaded event");
});
</script>
</head>
<body>
Test DOMContentLoaded
</body>
</html>
并且,有时(可能在 30 个请求中出现一次)DOMContentLoaded
事件会被跳过。
这可能是由于页面加载不正确造成的。但在日志中我看到:“脚本运行”。我想做一个重复的DOMContentLoaded
事件函数,如果DOMContentLoaded
事件被跳过,我的函数做了正确的工作。
我找到了这个解决方案:
1)
// The basic check
if(document.readyState === 'complete') {
// good to go!
}
// Polling for the sake of my intern tests
var interval = setInterval(function() {
if(document.readyState === 'complete') {
clearInterval(interval);
done();
}
}, 100);
2)
HTMLDocument.prototype.ready = function () {
return new Promise(function(resolve, reject) {
if (document.readyState === 'complete') {
resolve(document);
} else {
document.addEventListener('DOMContentLoaded', function() {
resolve(document);
});
}
});
}
document.ready().then(...);
3)
document.addEventListener('readystatechange', function docStateChange(e) {
if(e.target.readystate === 'complete') {
e.target.removeEventListener('readystatechange', docStateChange);
done();
}
});
4)
// This is needed to prevent onreadystatechange being run twice
var ready = false;
document.onreadystatechange = function() {
if (ready) {
return;
}
// interactive = DOMContentLoaded & complete = window.load
if (document.readyState == 'interactive' || document.readyState == 'complete') {
ready = true;
// init you code here
}
};
但哪种解决方案更正确?这些之间有什么区别?