Skip to content

Instantly share code, notes, and snippets.

@kalley
Created November 4, 2013 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalley/7303878 to your computer and use it in GitHub Desktop.
Save kalley/7303878 to your computer and use it in GitHub Desktop.
(function($) {
var head = $('head');
$.cssCapture = function(selectors, manipulate) {
var stylesheets = document.styleSheets,
selectors = selectors.split(/\s*,\s*/),m
promises = [],
matched = [],
newStyles = [];
$.each(stylesheets, function() {
var rules = this.cssRules;
if ( ! rules ) return;
$.each(rules, function() {
for ( var i = 0, l = selectors.length; i < l; ++i ) {
var regex = new RegExp('^\\' + selectors[i] + '$');
if ( this.type === 1 ) {
var ruleSelectors = this.selectorText.split(/\s*,\s*/),
matches = false;
for ( var j = 0, m = ruleSelectors.length; j < m; ++j ) {
if ( ruleSelectors[i].match(regex) ) {
matches = true;
break;
}
}
if ( matches && this.style.backgroundImage.match(/url\(/) ) {
matched.push(this.selectorText);
promises.push($.capture(this.style.backgroundImage.replace(/.*?url\(['"]?(.*?)['"]?\)/, "$1")));
}
}
}
});
});
var deferred = $.when.apply($, promises);
deferred.then(function() {
function done() {
var stylesheet = stylesheets[stylesheets.length - 1];
$.each(arguments, function(i) {
stylesheet.insertRule(matched[i] + '{background-image:url(' + ( this.src ? this.src : this ) + ')}', stylesheet.cssRules.length);
});
}
if ( manipulate && $.isFunction(manipulate) ) {
return manipulate.apply(done, arguments);
}
done.apply(null, arguments);
});
return deferred.promise();
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment