Skip to content

Instantly share code, notes, and snippets.

@paul-bjorkstrand
Created January 18, 2014 17:36
Show Gist options
  • Save paul-bjorkstrand/8493638 to your computer and use it in GitHub Desktop.
Save paul-bjorkstrand/8493638 to your computer and use it in GitHub Desktop.
Register, handle, and trigger custom ready events in jQuery. This facility simplifies the handling of ready events aside from the global document ready. This could help avoid different pieces of javascript contending for $.holdReady, and allows applications wait until only what they need is complete.
(function($) {
"use strict";
var readys = {};
function newReady(name) {
Object.defineProperty(
$,
name, {
enumerable: false,
configurable: false,
writable: false,
value: function(fn) {
readys[name].then(fn);
}
});
readys[name] = $.Deferred();
}
$.registerReady = function(name) {
if ($[name] || $.hasOwnProperty(name)) {
throw new Error("Property $." + name + " has already been defined. Please use another property name for the custom ready");
}
newReady(name);
};
$.triggerReady = function(name) {
readys[name].resolve();
};
$.readyStatus = function(name) {
return readys[name].status();
};
})($);
// example usage.
$.registerReady("customReady");
$.customReady(function() {
console.log("custom ready event");
});
$.triggerReady("customReady");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment