Created
July 22, 2015 09:36
-
-
Save yoavniran/2786f46f3ccb1e947c3a to your computer and use it in GitHub Desktop.
cross-browser dom ready helper
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
(function (doc, w) { | |
"use strict"; | |
var readyCallbacks = [], | |
docLoadEv = "DOMContentLoaded", | |
ready = (document.readyState === "complete"); | |
function registerForReadyEvent(fn) { | |
if (ready) { //already ready, execute immediately | |
fn(w); | |
} | |
else { | |
readyCallbacks.push(fn); | |
} | |
} | |
function waitForReadyEvent() { | |
if (!ready) { //register using different ways for cross-browser support. the first one fired "wins" | |
doc.addEventListener(docLoadEv, readyHandler); | |
w.onload = readyHandler; | |
doc.onload = readyHandler; | |
} | |
} | |
function readyHandler() { | |
if (!ready) { | |
ready = true; | |
doc.removeEventListener(docLoadEv, readyHandler); | |
w.onload = null; | |
doc.onload = null; | |
fireReadyCallbacks(); | |
} | |
} | |
function fireReadyCallbacks() { | |
readyCallbacks.forEech(function (fn) { //execute any callbacks waiting | |
fn(w); | |
}); | |
readyCallbacks.splice(0); | |
} | |
waitForReadyEvent(); | |
return registerForReadyEvent; | |
})(document, window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment