JSFiddle - React, Tailwind, and code Playground
JavaScript
// Uncomment to make it even more noticable:
/*const s = document.createElement('script');
s.src = 'https://1.1.1.1/slownotexists.js';
document.head.appendChild(s);*/
const $doc = document;
document.addEventListener('readystatechange', () => console.log('readyState: ' + document.readyState));
document.addEventListener('DOMContentLoaded', () => console.log('DOMContentLoaded'));
console.log('script loaded');
setupWaitForBodyLoad(function(){console.log('body load done!');});
////////////////////////////////////////////////////////////////////////////
// Setup code which waits for the body to be loaded and then calls the
// callback function
function setupWaitForBodyLoad(callback) {
function isBodyLoaded() {
return (/loaded|complete/.test($doc.readyState));
}
var bodyDone = isBodyLoaded();
if (bodyDone) {
console.log('body is already loaded');
callback();
return;
}
// If the page is not already loaded, setup some listeners and timers to
// detect when it is done.
function onBodyDone() {
if (!bodyDone) {
console.log('onBodyDone');
bodyDone = true;
callback();
if ($doc.removeEventListener) {
$doc.removeEventListener("DOMContentLoaded", onBodyDone, false);
}
if (onBodyDoneTimerId) {
clearInterval(onBodyDoneTimerId);
}
}
}
// For everyone that supports DOMContentLoaded.
if ($doc.addEventListener) {
$doc.addEventListener("DOMContentLoaded", onBodyDone, false);
}
// Fallback. If onBodyDone() gets fired twice, it's not a big deal.
var onBodyDoneTimerId = setInterval(function() {
console.log('interval tick');
if (isBodyLoaded()) {
console.log('interval tick noticed body load');
onBodyDone();
}
}, 50);
}
////////////////////////////////////////////////////////////////////////////