Skip to content

Instantly share code, notes, and snippets.

@mdellanoce
Created September 1, 2012 17:59
Show Gist options
  • Star 57 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save mdellanoce/3581792 to your computer and use it in GitHub Desktop.
Save mdellanoce/3581792 to your computer and use it in GitHub Desktop.
CSS3 caching
(function($) {
function parseImagesFromCSS(doc) {
var i, j,
rule,
image,
pattern = /url\((.*)\)/,
properties = ['background-image', '-webkit-border-image'],
images = {};
if (doc.styleSheets) {
for (i = 0; i < doc.styleSheets.length; ++i) {
images = $.extend(images, parseImagesFromCSS(doc.styleSheets[i]));
}
} else if (doc.cssRules) {
for (i = 0; i < doc.cssRules.length; ++i) {
rule = doc.cssRules[i];
if (rule.styleSheet) {
images = $.extend(images, parseImagesFromCSS(rule.styleSheet));
} else if (rule.style) {
for (j=0; j < properties.length; j++) {
image = pattern.exec(rule.style.getPropertyValue(properties[j]));
if (image && image.length === 2) {
images[image[1]] = image[0];
}
}
}
}
}
return images;
};
$.extend({
preload: {
images: function(doc) {
doc = doc || document;
var images = $.map(parseImagesFromCSS(doc), function(url) { return url; }),
head = doc.getElementsByTagName('head')[0],
style = doc.createElement('style');
style.type = 'text/css';
style.id = 'preload';
style.innerHTML = 'body::after { content: ' + images.join(' ') + '; display: none; }';
head.appendChild(style);
}
}
});
})(jQuery);
@majerski
Copy link

majerski commented Apr 8, 2014

How to use it? :)

@majerski
Copy link

majerski commented Apr 8, 2014

jQuery(function($) { $.preload.images(document) });

@ilyakar
Copy link

ilyakar commented Jun 8, 2014

Amazing little script. Thanks for it.

@odelbos
Copy link

odelbos commented Apr 8, 2015

I think you have to remove all inlined images with URLs such as : url(data:....) to avoid the following problem :

Import data url images

Because it's a nonsense to preload inlined images.

So you probably have to remove from "images" array all images matching the pattern : /url\(data/

Something of this kind :

for (j=0; j < properties.length; j++) {
  url = rule.style.getPropertyValue(properties[j]);
  image = pattern.exec(url);
  if (image && image.length === 2 && ! /url\(data/.exec(url)) {
    images[image[1]] = image[0];
  }
}

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