Skip to content

Instantly share code, notes, and snippets.

@danielo515
Forked from donut/getBGImgURLsFromCSSs.js
Last active May 3, 2016 15:49
Show Gist options
  • Save danielo515/9f7a7bb5435a7578c76b226eb63b39ea to your computer and use it in GitHub Desktop.
Save danielo515/9f7a7bb5435a7578c76b226eb63b39ea to your computer and use it in GitHub Desktop.
Builds a list of images found in the linked style sheets
window.npup = (function (doc) {
var sheets = doc.styleSheets;
var hash = {}, sheet, rules, rule, url, match;
// loop the stylesheets
for (var sheetIdx=0, sheetsLen=sheets.length; sheetIdx<sheetsLen; ++sheetIdx) {
sheet = sheets[sheetIdx];
// ie or w3c stylee rules property?
rules = sheet.rules ? sheet.rules : sheet.cssRules;
// loop the rules
for (var ruleIdx=0, rulesLen=rules.length; ruleIdx<rulesLen; ++ruleIdx) {
rule = rules[ruleIdx];
if (rule.selectorText && rule.style.cssText) {
// check if there's a style setting we're interested in..
if (rule.style.cssText.match(/background/)) {
// ..and if it has an url in it, put it in the hash
match = /url\(([^)]*)\)/.exec(rule.style.cssText);
if (match) {hash[match[1]] = true;}
}
}
}
}
// return an array of unique urls
var urls = [];
for (url in hash) {urls.push(url);}
// export a getter for what we found
return {
getBackgroundUrls: function () { return urls;}
};
})(document); // submit reference to the document of interest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment