Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active April 11, 2016 19:28
Show Gist options
  • Save softwarespot/2fa1080e395bf72ffe1f8314da756591 to your computer and use it in GitHub Desktop.
Save softwarespot/2fa1080e395bf72ffe1f8314da756591 to your computer and use it in GitHub Desktop.
Modern day DOM ready
var dom = (function dom(window, document) {
// Based on the idea of jQuery 3
var _resolveReady;
var _isReady = false;
var _listReady = new window.Promise(function promiseReady(resolve) {
_resolveReady = resolve;
});
// Check if the DOM has completed loading or is not in a loading state
if (document.readyState === 'complete' || document.readyState !== 'loading') {
_domComplete();
} else {
// Use the handy event callback
document.addEventListener('DOMContentLoaded', _domComplete);
// Fallback to when the window has been fully loaded. This will always be called
window.addEventListener('load', _domComplete);
}
// Public API
return {
ready: ready,
};
/**
* Invoke a function once the DOM has loaded
*
* @param {function} fn Callback function to invoke
* @return {promise} A promise that is resolved once the DOM is ready
*/
function ready(fn) {
if (typeof fn === 'function') {
_listReady.then(fn);
}
return new Promise(function promise(resolve /* , reject */) {
_listReady.then(function then() {
resolve();
});
});
}
/**
* Callback function for the DOM ready addEventListener calls
*
* @return {undefined}
*/
function _domComplete() {
if (_isReady) {
return;
}
// Cache that the DOM is ready and resolve the promise
_isReady = true;
_resolveReady();
// Clear up the event handlers
document.removeEventListener('DOMContentLoaded', _domComplete);
window.removeEventListener('load', _domComplete);
}
}(window, window.document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment