I made a simple page for testing:
<!DOCTYPE html>
//
console.log("script run");
//
document.addEventListener('DOMContentLoaded', function(event) {
//
alert("DOMContentLoaded event");
});
Test DOMContentLoaded
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?
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)