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.
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.
I found this solutions:
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
}
};
But which of the solutions is more correct? And what is the difference between these?