jQuery CSS Image Preloader


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



Copy this code and paste it in your HTML
  1. jQuery.preloadCssImages = function(){
  2.  
  3. var allImgs = [];//new array for all the image urls
  4. var k = 0; //iterator for adding images
  5. var sheets = document.styleSheets;//array of stylesheets
  6.  
  7. for(var i = 0; i<sheets .length; i++){//loop through each stylesheet
  8.  
  9. var cssPile = '';//create large string of all css rules in sheet
  10. var csshref = (sheets[i].href) ? sheets[i].href : 'window.location.href';
  11. var baseURLarr = csshref.split('/');//split href at / to make array
  12.  
  13. baseURLarr.pop();//remove file path from baseURL array
  14.  
  15. var baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
  16.  
  17. if(baseURL!="") baseURL+='/'; //tack on a / if needed
  18.  
  19. if(document.styleSheets[i].cssRules){//w3
  20.  
  21. var thisSheetRules = document.styleSheets[i].cssRules; //w3
  22.  
  23. for(var j = 0; j<thisSheetRules.length; j++){
  24. cssPile+= thisSheetRules[j].cssText;
  25. }
  26. }
  27. else {
  28. cssPile+= document.styleSheets[i].cssText;
  29. }
  30.  
  31. //parse cssPile for image urls and load them into the DOM
  32. var imgUrls = cssPile.match(/[^\(]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename"
  33.  
  34. if(imgUrls != null && imgUrls.length>0 && imgUrls != ''){//loop array
  35.  
  36. var arr = jQuery.makeArray(imgUrls);//create array from regex obj
  37.  
  38. jQuery(arr).each(function(){
  39. allImgs[k] = new Image(); //new img obj
  40. allImgs[k].src = (this[0] == '/' || this.match('http://')) ? this : baseURL + this; //set src either absolute or rel to css dir
  41. k++;
  42. });
  43. }
  44. }//loop
  45. return allImgs;
  46. }

URL: http://ajaxian.com/archives/preloading-images-with-jquery

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.