Skip to content

Instantly share code, notes, and snippets.

@swashcap
Last active August 29, 2015 14:26
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 swashcap/a739e86ba9fbe178314d to your computer and use it in GitHub Desktop.
Save swashcap/a739e86ba9fbe178314d to your computer and use it in GitHub Desktop.
CSS Background Images
var pattern = /url\(([^)]+)/g;
var cssBackgrounds = [];
var results = [];
var matches;
// Loop over every stylesheet and get the background image references in every
// `background: url(...)`
for (var i = 0, il = document.styleSheets.length; i < il; i++) {
for (var j = 0, jl = document.styleSheets[i].rules.length; j < jl; j++) {
if (document.styleSheets[i].rules[j].cssText.indexOf('url(') !== -1) {
matches = pattern.exec(document.styleSheets[i].rules[j].cssText);
if (
matches &&
matches.length > 1 &&
matches[1].indexOf('data') !== 0 &&
cssBackgrounds.indexOf(matches[1]) === -1
) {
cssBackgrounds.push(matches[1]);
}
}
}
}
// Send `fetch` requests for every background image
for (var k = 0, kl = cssBackgrounds.length; k < kl; k++) {
results.push(fetch(cssBackgrounds[k]));
}
// Log out bad background images
Promise.all(results).then(function(results) {
return results.filter(function(response) {
return (response.status < 200 || response.status >= 300);
}).map(function(response) {
return response.url;
});
}).then(function(badBackgrounds) {
console.log('Bad CSS Background images:');
badBackgrounds.forEach(function(background) {
console.log(background);
});
});
@swashcap
Copy link
Author

swashcap commented Aug 4, 2015

This will only work with browsers that have support for fetch and Promise (Chrome >=42, FF >=39, Opera >=30).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment