jQuery Preload CSS Images

Share this article

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        

			jQuery(arr).each(function(){
				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
				k++;
			});
		}
	}//loop
	return allImgs;
}

Usage

//preload only
$.preloadCssImages();

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

This is the array of images!

preload-images

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQueryPreload background images
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form