Last active
August 29, 2015 14:26
-
-
Save swashcap/a739e86ba9fbe178314d to your computer and use it in GitHub Desktop.
CSS Background Images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will only work with browsers that have support for
fetch
andPromise
(Chrome >=42, FF >=39, Opera >=30).