Skip to content

Instantly share code, notes, and snippets.

@sgromkov
Created July 21, 2020 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgromkov/ce703a688851118487d72d51363d9382 to your computer and use it in GitHub Desktop.
Save sgromkov/ce703a688851118487d72d51363d9382 to your computer and use it in GitHub Desktop.
Call callback when DOMContentLoaded is fired, even it has already been fired.
/**
* Call callback when DOMContentLoaded is fired,
* even it has already been fired.
*
* @see https://stackoverflow.com/a/35996985
*
* @function callAfterDomContentLoaded
* @param {function} callback
* A function that should be fired
*/
const callAfterDomContentLoaded = function (callback) {
if (/complete|interactive|loaded/.test(document.readyState)) {
// In case the document has finished parsing, document's readyState will
// be one of "complete", "interactive" or (non-standard) "loaded".
callback();
} else {
// The document is not ready yet, so wait for the DOMContentLoaded event
document.addEventListener('DOMContentLoaded', callback, false);
}
}
export default callAfterDomContentLoaded;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment