Created
February 28, 2025 12:29
-
-
Save paponius/cea050ff129cc34df1631dfcc50b8ee0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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