Created
May 30, 2017 14:19
-
-
Save DmitryMyadzelets/855fa8a4f976e64a943cc915aba317b6 to your computer and use it in GitHub Desktop.
When a web page is ready for manipulation. Altrernative for jQuery ready()
This file contains 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
// Invokes callback when DOM is ready for manipulation | |
// Usage: ready(function () {}); | |
function ready(callback) { | |
// Motivation: | |
// https://gomakethings.com/a-native-javascript-equivalent-of-jquerys-ready-method/ | |
// Docs: | |
// https://developer.mozilla.org/en/docs/Web/API/Document/readyState | |
var loading, done; | |
done = function () { | |
document.removeEventListener('readystatechange', loading); | |
window.removeEventListener('load', done); | |
callback(); | |
}; | |
loading = function () { | |
if (document.readyState === 'loading') { | |
return true; | |
} | |
done(); | |
}; | |
if (loading()) { | |
document.addEventListener('readystatechange', loading); | |
window.addEventListener('load', done); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment