Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.