Skip to content

Instantly share code, notes, and snippets.

@kgn
Last active September 27, 2015 05:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kgn/1218824 to your computer and use it in GitHub Desktop.
Save kgn/1218824 to your computer and use it in GitHub Desktop.
A javascript snippet that will preload all images defined in the styles sheets.
(function(){
var styles, matches, match, url, img = new Image(), loaded = [];
function forEach(a,c){if(a&&c){for(var i=0;i<a.length;++i){c.call(a[i])}}};
forEach(this.styleSheets, function(){
forEach(this.rules, function(){
forEach(styles=this.style, function(){
if(this.toString() !== 'background-image')return;
if(!(matches=styles[this].match(/url\([^\)]+\)/g)))return;
forEach(matches, function(){
if(!(match=this.match(/url\(([^\)]+)\)/)))return;
if(loaded.indexOf(url=match[1]) !== -1)return;
loaded.push(img.src = url);
});
});
});
});
}).call(document)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment