Created
November 4, 2013 15:08
-
-
Save kalley/7303878 to your computer and use it in GitHub Desktop.
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($) { | |
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