Update: A New & Improved jQuery Script to Automatically Preload images from CSSUpdate: A New & Improved jQuery Script to Automatically Preload images from CSS

Bookmark on del.icio.us

When we first launched the lab, we released a jQuery plugin that automatically preloads all images referenced in CSS files. We’ve found the script to be incredibly helpful in developing snappy applications where images are always ready when we need them. This post describes a significant update to the script which will make it even easier to integrate in existing projects.

The concept behind this script

If you’re interested in reading about how and why we developed this script, please read our original article. Keep in mind that this update provides a new version of the code which is highly recommended over the first version.

New version improvements

Among other small improvements, this release allows preloading images from any directory specified in the CSS. Also offers load status updates for text and image-based load bars.

Load images from anywhere; no arguments!

The first version of the script preloaded images from a single directory. Unfortunately, this limitation meant the script would not work well with web applications using images located in several directories or even other web sites entirely. This updated version loads images relative to their stylesheet’s url, allowing them to load no matter where they are located on the web. The new code is detailed below:

The source code

The source code for this plugin can be downloaded here: preloadCssImages.jQuery_v5.js

How do I use it?

To use this plugin, be sure you’ve attached the jQuery javascript library and preloadCssImages.jQuery_v5.js to your page, and call $.preloadCssImages(); when the DOM is ready. Like this:


$(document).ready(function(){
  $.preloadCssImages();
});

This will parse though all of your attached CSS files and preload any images it finds referenced in them.

A quick demo

The example below uses our script to parse through a sample stylesheet which we’ve linked to the page. The sample stylesheet has background images specified for elements that don’t actually exist on the page, so the images specified are not currently loaded. Clicking the button below will load them into the DOM. For example purposes, we’ll write the loaded images into the page as well. The optional load status elements are shown upon load.

View this example in a new window

For a simplified demo page that doesn’t use a visual preloader, view this page: http://www.filamentgroup.com/examples/preloadImages/index_v5b.php

  1. No comments yet.

  1. No trackbacks yet.