This is a useful way of pre-loading css images before rendering JavaScript/jQuery animation for example. This Script is a little jQuery plugin that caches all images referenced in linked/imported CSS files (it iterates through each rule in each stylesheet attached and if the rule’s value contains an image URL, it loads the image, thus ensuring it’s available in the cache when used in the document.

The Preload CSS Images Function

jQuery.preloadCssImages = function(){

	var allImgs = [];//new array for all the image urls  
	var k = 0; //iterator for adding images
	var sheets = document.styleSheets;//array of stylesheets

	for(var i = 0; i0 && imgUrls != ''){//loop array

			var arr = jQuery.makeArray(imgUrls);//create array from regex obj        

				allImgs[k] = new Image(); //new img obj
				allImgs[k].src = (this[0] == '/' || this.match('http://')) ? this : baseURL + this;     //set src either absolute or rel to css dir
	return allImgs;


//preload only

//load into array
var preloadedImgs = $.preloadCssImages();

This is the array of images!


Tags: jquery preload css, jQuery Preload Images, Preload background images
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • Jeremy

    Thanks for this script, but how can i get the list of all images?

    • jquery4u

      @Jeremy – The list of all image is stored in variable imgUrls. Cheers

  • Ethan

    Uncaught SyntaxError: Unexpected token ; jquery.preloadCssImages.js:34

    • Kumroi

      if(imgUrls != null && imgUrls.length>0 && imgUrls != ”)

      Change && for the apropriate char &&

      • kumori

        “& amp ; ” i mean…

        • Alexvb6

          You also need to replace < by <

          • Alexvb6

            I mean you need to replace “& lt ;” by <

  • Carla

    Sam, this executes successfully, but my rollovers still aren’t loaded.

  • Bassel Issa

    Hi Sam, nice work, but i think you need to handle the base64 images like background-image:url(data:image/gif;base64,R0lGODlhCgAKAIAAAOLi4 ……..)

  • rafæl

    Exactly what I was looking for … thx a lot for sharing …

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.