★ Snippet O’ the Week: Preload images with jQuery
March 29th, 2012 by Patrick Cox | No Comments
The popularity (and rightly so) of responsive web design is growing and while it’s fairly easy to set up flexible grids and text styling via medi queries, images tend to be harder to work with in a responsive design. Slow loading images can be a big deal to users especially when your site it trying to load images that just aren’t being used – like different header backgrounds for different display sizes. A great way to make sure you images load quicker is to preload your images in the background while the rest of the page is loading.
I found the following snippet at Engineered Web after I failed to find any snippets that worked correctly. View the source code here for the full explanation of the code.
Use this script:
(function($) { var cache = []; // Arguments are image paths relative to the current page. $.preLoadImages = function() { var args_len = arguments.length; for (var i = args_len; i--;) { var cacheImage = document.createElement('img'); cacheImage.src = arguments[i]; cache.push(cacheImage); } } })(jQuery)
Call the script by:
jQuery.preLoadImages("largeHeader.png","medHeader.png","smallHeader.png");
Good luck!








