[英]JavaScript DOMContentLoaded event is skipped
I made a simple page for testing: 我做了一个简单的页面进行测试:
<!DOCTYPE html>
<html>
<head>
<script>
//
console.log("script run");
//
document.addEventListener('DOMContentLoaded', function(event) {
//
alert("DOMContentLoaded event");
});
</script>
</head>
<body>
Test DOMContentLoaded
</body>
</html>
And, sometimes (maybe once in 30 requests) DOMContentLoaded
event is skipped. 而且,有时(可能是30个请求中的一个) DOMContentLoaded
事件被跳过。
Perhaps this is due to incorrect loading of the page. 也许这是由于页面加载不正确造成的。 But in log I see: "script run". 但是在日志中,我看到:“脚本运行”。 I want make a duplicate DOMContentLoaded
event function, and if DOMContentLoaded
event is skipped, my function did the right job. 我想制作一个重复的DOMContentLoaded
事件函数,如果跳过DOMContentLoaded
事件,则我的函数执行了正确的工作。
I found this solutions: 我找到了以下解决方案:
1) 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) 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) 3)
document.addEventListener('readystatechange', function docStateChange(e) {
if(e.target.readystate === 'complete') {
e.target.removeEventListener('readystatechange', docStateChange);
done();
}
});
4) 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
}
};
But which of the solutions is more correct? 但是,哪种解决方案更正确? And what is the difference between these? 这些之间有什么区别?
Worked for me: 为我工作:
<!DOCTYPE html> <html> <head> <script> // This is needed to prevent onreadystatechange being run twice var ready = false; document.onreadystatechange = function () { if (ready) { alert(document.getElementById('testing').getAttribute("class")); return; } // interactive = DOMContentLoaded & complete = window.load if (document.readyState === 'interactive' || document.readyState === 'complete') { ready = true; // init your code here } }; </script> </head> <body> Test DOMContentLoaded <p> <button type='button' id='testing' class='btn border3'>a button</button> </p> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.