Skip to content

Instantly share code, notes, and snippets.

@vyach-vasiliev
Forked from donut/getBGImgURLsFromCSSs.js
Last active June 11, 2017 14:41
Show Gist options
  • Save vyach-vasiliev/b57985580bada94f6027233f6dce2b77 to your computer and use it in GitHub Desktop.
Save vyach-vasiliev/b57985580bada94f6027233f6dce2b77 to your computer and use it in GitHub Desktop.
Builds a list of images found in the linked style sheets
/* Builds a list of images found in the linked style sheets
*
* Adapted from stackoverflow.com/questions/2430503/list-of-all-background-images-in-dom/2453880#2453880
*
* This method has the advantage of finding URLs for background images that no
* element in the DOM uses yet.
* Author: Donovan Mueller @donut (https://github.com/donut)
* Contributors: Vyacheslav Vasiliev @vyach-vasiliev (https://gist.github.com/vyach-vasiliev)
*
* @return {array}
* List of unique image URLs as specified in the style sheets.
* data:image/...
* http://host.com/...
* /folder/...
------------------------------------------------------------------------- */
function getBGImgURLsFromCSSs()
{
if (getBGImgURLsFromCSSs.BGImgURLs) {
return getBGImgURLsFromCSSs.BGImgURLs;
}
var sheets = document.styleSheets;
var hash = {}, sheet, rules, rule, url, match;
// loop the stylesheets
for (var s = 0, sheet_count = sheets.length; s < sheet_count; ++s) {
sheet = sheets[s];
// ie or w3c stylee rules property?
try {
// Some browsers will throw security exceptions when trying to access
// stylesheets form different domains (an example would be when using
// TypeKit).
rules = sheet.rules ? sheet.rules : sheet.cssRules;
}
catch (exception) { continue; }
if (!rules) continue;
// loop the rules
for (var r = 0, rule_count = rules.length; r < rule_count; ++r) {
rule = rules[r];
if (rule.selectorText && rule.style.cssText) {
// check if there's a style setting we're interested in..
if (rule.style.cssText.match(/background/i)) {
// ..and if it has a URL in it, put it in the hash
match = /url\(['"]?([^)'"]*)['"]?\)/i.exec(rule.style.cssText);
if (match) {
url = match[1]
// Do we need to make the URL absolute?
if (url.search(/^(?:http|\/)/i) !== 0) {
// Yes.
if(sheet.href)
url = sheet.href.replace(/[^\/]+$/, '') + url;
}
hash[url] = true;
}
} // if background style
} // if has rule
} // for each rule
} // for each stylesheet
// return an array of unique URLs
var urls = [];
for (url in hash) { urls.push(url); }
// Save in case this gets called later.
getBGImgURLsFromCSSs.BGImgURLs = urls;
return getBGImgURLsFromCSSs.BGImgURLs;
}
// getBGImgURLsFromCSSs()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment