Preload all bg images referenced in CSS


/ Published in: JavaScript
Save to your folder(s)

will preload any background image referenced in your CSS.


Copy this code and paste it in your HTML
  1. (function($) {
  2. function parseImagesFromCSS(doc) {
  3. var i, j,
  4. rule,
  5. image,
  6. pattern = /url\((.*)\)/,
  7. properties = ['background-image', '-webkit-border-image'],
  8. images = {};
  9.  
  10. if (doc.styleSheets) {
  11. for (i = 0; i < doc.styleSheets.length; ++i) {
  12. images = $.extend(images, parseImagesFromCSS(doc.styleSheets[i]));
  13. }
  14. } else if (doc.cssRules) {
  15. for (i = 0; i < doc.cssRules.length; ++i) {
  16. rule = doc.cssRules[i];
  17. if (rule.styleSheet) {
  18. images = $.extend(images, parseImagesFromCSS(rule.styleSheet));
  19. } else if (rule.style) {
  20. for (j=0; j < properties.length; j++) {
  21. image = pattern.exec(rule.style.getPropertyValue(properties[j]));
  22. if (image && image.length === 2) {
  23. images[image[1]] = image[0];
  24. }
  25. }
  26. }
  27. }
  28. }
  29. return images;
  30. };
  31. $.extend({
  32. preload: {
  33. images: function(doc) {
  34. doc = doc || document;
  35. var images = $.map(parseImagesFromCSS(doc), function(url) { return url; }),
  36. head = doc.getElementsByTagName('head')[0],
  37. style = doc.createElement('style');
  38. style.type = 'text/css';
  39. style.id = 'preload';
  40. style.innerHTML = 'body::after { content: ' + images.join(' ') + '; display: none; }';
  41. head.appendChild(style);
  42. }
  43. }
  44. });
  45. })(jQuery);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.