Created
May 20, 2014 17:30
-
-
Save radist2s/7f342f290d5ece2ddc71 to your computer and use it in GitHub Desktop.
Simple ready checker (simple deferred) + Dom ready Checker
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
var ReadyChecker = (function () { | |
/** | |
* Simple Deferred | |
* @param {Function} readyCheckerResolver | |
* @param {Function} [callback] | |
* @constructor | |
*/ | |
function ReadyChecker (readyCheckerResolver, callback) { | |
this.onReady(callback) | |
var _this = this | |
if (typeof readyCheckerResolver === 'function') { | |
readyCheckerResolver(function() { | |
_this.resolve.apply(_this, arguments) | |
}) | |
} | |
return this | |
} | |
ReadyChecker.prototype.onReady = function (callback) { | |
if (this.isReady) { | |
runCallback(callback, this._resolvedContext) | |
return this | |
} | |
this.onReadyCallbacks = this.onReadyCallbacks || [] | |
if (typeof callback == 'function') { | |
this.onReadyCallbacks.push(callback) | |
} | |
return this | |
} | |
/** | |
* @param [context] | |
* @returns {ReadyChecker} | |
*/ | |
ReadyChecker.prototype.resolve = function (context) { | |
if (this.isReady) { | |
return this | |
} | |
this.isReady = true | |
this._resolvedContext = context | |
runCallback.call(this, this.onReadyCallbacks, this._resolvedContext) | |
return this | |
} | |
var runCallback = function (callbacks, context) { | |
if (typeof callbacks === 'function') { | |
callbacks = [callbacks] | |
} | |
if (!(callbacks instanceof Array)) { | |
return | |
} | |
if (callbacks.length) { | |
var i | |
for (i in callbacks) { | |
if (!callbacks.hasOwnProperty(i)) { | |
continue | |
} | |
var readyCallback = callbacks[i] | |
if (typeof readyCallback === 'function') { | |
readyCallback.call(context || window) | |
} | |
callbacks.splice(i) | |
} | |
} | |
} | |
return ReadyChecker | |
})(); | |
// Usage: | |
/** | |
* Simple DOM Ready checker | |
* @param callback | |
*/ | |
var domReadyChecker | |
function domReady (callback) { | |
// Any DOM_Ready checker | |
domReadyChecker = domReadyChecker || new ReadyChecker(function (ready) { | |
if (document.readyState === 'complete') { | |
ready() | |
return | |
} | |
if (document.addEventListener) { | |
var pageReadyEvent = function () { | |
document.removeEventListener('DOMContentLoaded', pageReadyEvent, false) | |
window.removeEventListener('load', pageReadyEvent, false) | |
ready() | |
} | |
document.addEventListener('DOMContentLoaded', pageReadyEvent, false) | |
window.addEventListener('load', pageReadyEvent, false) | |
} | |
}) | |
domReadyChecker.onReady(callback) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment