/* 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. * * @return {array} * List of unique image URLs as specified in the style sheets. ------------------------------------------------------------------------- */ 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. 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()