Skip to content

Instantly share code, notes, and snippets.

@paponius
Created February 28, 2025 12:29
Show Gist options
  • Save paponius/cea050ff129cc34df1631dfcc50b8ee0 to your computer and use it in GitHub Desktop.
Save paponius/cea050ff129cc34df1631dfcc50b8ee0 to your computer and use it in GitHub Desktop.
// SNIPPET whenPageReady v1.3
// state: [interactive | complete]
// usage: whenPageReady(doStuff, 'interactive');
var whenPageReady = (handler, state = 'complete') => {
var eventName;
if (state === 'DOMContentLoaded') { state = 'interactive'; }
if (state === 'load') { state = 'complete'; }
if (state !== 'interactive' && state !== 'complete') {
console.warn('SCRIPTNAME: whenPageReady(): wrong STATE argument: ' + state + '. Defaulting to: "complete".');
state = 'complete';
}
if (state === 'interactive') { eventName = 'DOMContentLoaded'; }
if (state === 'complete') { eventName = 'load'; }
if (document.readyState !== 'complete' && (state === 'complete' || document.readyState !== 'interactive')) {
window.addEventListener(eventName, () => whenPageReady(handler, state));
// if (DEBUG) { console.log("SCRIPTNAME: whenPageReady(): page not ready. (readyState = '" + document.readyState + ', desired: ' + state); }
return;
}
// if (DEBUG) { console.log("SCRIPTNAME: whenPageReady(): page ready (readyState = '" + state + "')"); }
handler();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment