Skip to content

Instantly share code, notes, and snippets.

@JerrySievert
Forked from munro/jquery.partialReady.js
Created June 5, 2012 14:09
Show Gist options
  • Save JerrySievert/2875234 to your computer and use it in GitHub Desktop.
Save JerrySievert/2875234 to your computer and use it in GitHub Desktop.
jquery.partialReady.js
/*jslint browser: true, nomen: true */
/*global jQuery, console */
(function ($) {
'use strict';
var timer, timer_delay = 250, next_id = 0, selectors = {};
/**
* Keep checking the DOM for new selectors
*/
function handlePartials() {
console.profile('partialReady');
$.each(selectors, function (sel, cbs) {
$(sel).each(function () {
var elem = $(this);
$.each(cbs, function (_, cb) {
var key = 'partial-ready-' + cb.id;
if (!elem.data(key)) {
elem.data(key, true);
cb.fn.apply(elem, elem);
}
});
});
});
console.profileEnd('partialReady');
}
timer = setInterval(handlePartials, timer_delay);
$(function () {
clearInterval(timer);
handlePartials();
/**
* Dereference the memory
*/
selectors = null;
});
/**
* @param {String} selector CSS selector
* @param {Function} callback Callback function
*/
$.partialReady = function (selector, callback) {
var elems;
/**
* Page is already ready—so just fire the callback.
*/
if ($.isReady) {
elems = $(selector);
callback.call(elems, elems);
}
/**
* Appened the selector to the ready loop
*/
(selectors[selector] = selectors[selector] || []).push({
id: (next_id += 1),
fn: callback
});
};
/**
* Change the interval timer
* @param {Number} delay Optional delay
*/
$.partialReady.interval = function (delay) {
if (typeof delay === 'undefined') {
return timer_delay;
}
if (timer) {
clearInterval(handlePartials);
timer = setInterval(handlePartials, (timer_delay = delay));
}
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment