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

Posted by Scott on 06/04/2008

Topics:

10/31/08 Update: Many updates to performance, error handling, and browser bugs. Thanks Trixta!
7/24/08 Update: Fixed support for Opera and @import CSS (thanks http://marcarea.com/).
6/21/08 Update: This script is now updated with optional settings for load status, including a percentage bar! We also included a bug fix for IE when loading absolute image paths (Thanks Sam Pohlenz!). Details are below.

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.

Demo page

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

Additional options

Displaying Load Progress

You can optionally pass element selectors to the plugin which will receive updates on the load status. These settings are specified as statusTextEl and statusBarEl. The values must be jQuery selector strings, for example: $.preloadCssImages({statusTextEl: '#textStatus', statusBarEl: '#status'});. To make a preload bar, cut a background image to the same width as your status bar element and assign it to the background of your element in CSS. Be sure to set its background-repeat to 'no-repeat'. The script will handle the positioning.

Number of Simultaneous Requests Allowed

This feature was added by Trixta. The option simultaneousCacheLoading allows you to specify the number of simultaneous images to request at a time. It defaults to 2. If you plan to run this plugin while other assets are loading, you may want to set this option to 1, for browsers which can only handle 2 HTTP requests at a time.

Download preloadCssImages.jQuery_v5.js

This script is a jQuery plugin, meaning is is dependant on the incredible jQuery javascript library. If you feel particularly adventurous, this script could be easily ported to another library or written in plain old JavaScript as well. Feel free to grab the script and try it for yourself. We're always looking for ways to improve our scripts, so if you encounter any issues or have any questions or suggestions please leave a comment below.

Comments

Hi I dug your script and wanted to port it to Prototype.
So here it is: http://pastie.org/209498

Comment by JDD on 06/05  at  12:12 PM

@JDD: Nice work. You’ve given us some ideas where we can optimize ours as well! Thanks.

Comment by Scott (Filament) on 06/05  at  05:47 PM

This script appears to have a problem in IE, relating to the use of square brackets to get at a character index.

To fix, line 46 should be:
allImgs[k].src = (this.charAt(0) == ‘/’ || this.match(’http://’)) ? this : baseURL + this; //set src either absolute or rel to css dir

Otherwise, great plugin. Thanks!

Comment by Sam Pohlenz on 06/20  at  03:46 PM

@Sam: Thanks for commenting. What version of IE are you seeing a problem in? We just tested the demo page in 6 and 7 and see no problems.

Comment by Scott (Filament) on 06/20  at  03:58 PM

Scott, the demo page doesn’t trigger the issue as none of the URLs in the css begin with a forward slash.

Under IE 6 & 7 (at least on my machine), “mystring"[0] gives undefined, whereas “mystring”.charAt(0) gives the desired result of ‘m’.

The result is that presently under IE, any absolute css urls beginning with / will be fetched as if they were relative urls.

Comment by Sam Pohlenz on 06/20  at  04:24 PM

Thanks Sam. It’s an interesting case that we’ll have to look into. I tried pasting in your charAt change real quick and it caused errors for me in FF and Safari. Not sure what would cause those but we’ll have to take a look at this next week and see. Thanks for following up though, we’ll let you know when we figure out a fix for your case.

Comment by Scott (Filament) on 06/20  at  05:43 PM

Great work, this will really save a lot of time. Just concerned about IE issues though.

Comment by Abhimanyu Grover on 06/21  at  08:49 AM

6/21/08 Update: This script is now updated with optional settings for load status, including a percentage bar! We also included a bug fix for IE when loading absolute image paths (Thanks Sam Pohlenz!).

Comment by Scott (Filament) on 06/21  at  11:22 AM

Just a few suggestions :

Check the media type of the stylesheet :

var mediaText = typeof sheets[ i ].media.mediaText !== ‘undefined’ ? sheets[ i ].media.mediaText : sheets[ i ].media;
if ( mediaText.indexOf(’screen’) ) {
continue;
}

And check @import rules for csshref:

if ( csshref == null ) {// consider @import rules
for ( var z=0; z<sheets[ i ].cssRules.length; z++) {
if ( sheets[ i ].cssRules[z].constructor == CSSImportRule ) {
csshref = sheets[ i ].cssRules[z].href;
}
}
}

Consider @import rules, somebody may write it better smile

if(sheets[ i ].cssRules){//w3
var thisSheetRules = sheets[ i ].cssRules; //w3
for(var j = 0; j<thisSheetRules.length; j++){
if ( sheets[ i ].cssRules[j].constructor == CSSImportRule ) {
var importSheetRules = sheets[ i ].cssRules[j].styleSheet.cssRules;
for ( var x=0; x<importSheetRules.length; x++ ) {
cssPile+= importSheetRules[x].cssText;
}
} else {
cssPile+= thisSheetRules[j].cssText;
}
}
}
else {
if ( sheets[ i ].imports.length > 0 ) {
for (var m=0; m<sheets[ i ].imports.length; m++) {
cssPile+= sheets[ i ].imports[m].cssText
}
} else {
cssPile+= sheets[ i ].cssText;
}
}

Comment by Marc on 06/21  at  11:40 AM

@Marc: Great catch, thanks so much. We’ll add it in there ASAP!

Comment by Scott (Filament) on 06/21  at  11:50 AM

Have you tested it with Opera? I’m using Opera 9.5 on XP SP3 and it doesn’t work. The image URLs are like this:
http://www.filamentgroup.com/examples/preloadImages/&#x22http://www.filamentgroup.com/examples/preloadImages/images/bg_header.jpg
instead of this:
http://www.filamentgroup.com/examples/preloadImages/images/bg_header.jpg
(which is what I get with Fx, IE and Safari)

Comment by Antonio Bueno on 06/23  at  05:35 AM

@Antonio: Thanks, we’ll look into it. Looks like a regression in the last update.

Comment by Scott (Filament) on 06/23  at  08:34 AM

and how do i use this with body onload?? i dont want users to have to click

Comment by Michal on 08/07  at  04:58 AM

@Michal: You can refer to the section above “How do I use it?” for usage instructions, but basically, it’s a function that you can call whenever you’d like. The demo page runs on a click event because it’s easier to see what’s taking place that way.

To run it on dom ready:
$(function(){
$.preloadCssImages();
});

To run on body load:
$(’body’).load(function(){
$.preloadCssImages();
});

Comment by Scott (Filament) on 08/07  at  08:29 AM

Hi Scott,

very nice script. i needed something like this, but i had some problems with multiple css-files in different folders. so i fixed some bugs and improved style-parsing performance.

here you can find the script with a nice demo:
http://www.protofunc.com/scripts/jquery/cssImagePreload/

Comment by alexander on 08/09  at  01:22 PM

Receive “access is denied” on line 58.
cssPile+= sheets[ i ].cssText;

Could this be cause by a cross-domain issue?

Comment by Rick on 08/20  at  01:34 PM

Hi there, lovely plugin, only thing is, it doesnt seem to work with using fadein, I can see in statustext that its loaded, but on mouseover event, I can see firefox3 still loading the image - causing a flicker with rollover effect.

Any suggestions to why this is happening ?

Kind regards

zenmaster

Comment by Zenmaster on 08/24  at  04:41 AM

Hi there- I’m excited to try this out. Would you be able to say more specifically where you put the call to the script? In the head, the body, the bottom? I know you say “when the dom is ready” but I’m still getting my head around all this DOM stuff. Thanks!

Comment by Terrence on 09/04  at  01:41 PM

@Terrence: jQuery has a custom event that allows you to run code as soon as the DOM is ready (the elements are there but images aren’t yet loaded). You can use it like this:

$(document).ready(function(){
//put your DOM-related scripting here
});

Comment by Scott (Filament) on 09/04  at  01:48 PM

Hi,

Firebug gives the following error:

Security error” code: “1000
if(document.styleSheets[i].cssRules){//w3

I get this error when I access my website using http://www.raihaniqbal.net which basically points to http://www.raihaniqbal.org. But it works when I use the latter url.

Any idea?

Comment by Raihan on 09/17  at  12:46 AM

There’s a bug in your script, on or about line 40:

if ( sheets[i].cssRules[j].constructor == ‘CSSImportRule’ ) { //added support for @imported css - credit: http://marcarea.com/

should read instead:

if ( sheets[i].cssRules[j].constructor == CSSImportRule ) { //added support for @imported css - credit: http://marcarea.com/

Note the absence of quotes around CSSImportRule. The equivalence operation for the constructor needs to be made against an object, not a string.

Comment by Daniel Wright on 09/17  at  01:55 PM

@Daniel
This and some other bugs are fixed in this version:
http://www.protofunc.com/scripts/jquery/cssImagePreload/

I hope there will be an new bugfix and CPU- + http-performance release by Scott.

Comment by alex on 09/18  at  05:47 PM

“Paste the code above into your JavaScript file and run $.preloadCssImages(); when the DOM is ready.”

I’m with Terrence here. I can’t figure out how to actually use this. Your demo includes a button to click, which is I guess useful in some way, but it doesn’t really apply to a web page. I don’t want to have anyone click anything, I just want the css images to load silently. Once I have included the plugin & jquery scripts in the head, where exactly do I add code to a page to preload images?

Please talk to me like I’m pretty much an idiot regarding scripting, because I am!

Comment by AdrienneA on 10/21  at  05:46 PM

I *think* that what they mean is
1. Have a javascript file that is included in the <head> of your html page, where the code is kept.
2. In order to get the code to actually run, you have to wait for the dom to be ready… that means, wait until the entire page has loaded. The DOM is a way of visualizing the HTML structure of the page - <body> is a parent of <h2>, <li> is a child of <ul>, etc. And the way that jquery works is to go through the whole DOM structure (i.e. your HTML) and find exactly the right spot where it is supposed to DO SOMETHING. That SOMETHING is the javascript code that you included in your head. Finding WHERE to do that something is figured out by the $.preloadCssImages();, and so you can only do that command AFTER the entire page has loaded. You run that command by saying $.preloadCssImages();… again, this comes after the dom is created, so right at the end, before the </body> tag.

Anyone out there - I am still very new myself, so please correct me if I am wrong. (as I know you will)

Comment by Terrence on 10/21  at  06:00 PM

@AdrienneA: Sorry for the confusion, and thank you Terrence for helping to answer the question! The demo is just there to illustrate images being loaded in from the stylesheet, which in reality is something the user would probably not see and would not have to initialize through a click, so I can see how it could be misleading.

Here’s the basic gist of using this script:
First of all, this script relies on jQuery, so if you don’t already have jQuery attached to your page, you’ll need to download it from jQuery.com or link to the google version of it here: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js

Once you’ve attached jQuery and our script to your page, you can preload your CSS images by calling $.preloadCssImages();. As Terrence pointed out though, this won’t work properly unless the HTML on your page has finished loading. Fortunately, jQuery has an event which lets you run code when your HTML finishes loading, and it looks like this:

$(document).ready();

To use this, just pass a function into the ready event and put all your DOM-related jQuery code inside it. Like this:

$(document).ready(function(){
//DOM-related jQuery code goes here
});

Anything inside that ready event will execute when the page is ready to be manipulated, and that’s where you’ll put your call to preloadCSSImages as well. So here it is, in full:

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

Let me know if that clarifies things for you.

Comment by Scott (Filament) on 10/22  at  09:08 AM

Here is a demo page that uses preloadCSSImages in its most basic configuration. Hopefully, this will clear up the confusion around how to use this plugin, as it really is quite simple to implement.

View the source of this page:
http://www.filamentgroup.com/examples/preloadImages/index_v4b.php

We will update the article soon with better usage instructions.
Thanks!

Comment by Scott (Filament) on 10/22  at  09:40 AM

Thanks, Scott and Terrence. I’ll give it a whirl!

Comment by AdrienneA on 10/22  at  07:39 PM

Thanks for your detailed instructions. This plugin is great! I recently made a site with CSS rollovers, but had big images so there was quite a lag for the rollovers to appear.  Now they really snap up. Take a look if you’d like:

jainabee.com

IE doesn’t load the images quite as nicely as FF, but there you go :-(

Overall the script really improves the page’s performance. Thanks!

Comment by AdrienneA on 10/23  at  06:31 PM

OK!! So I’ve read all the comments, articles, and got everything installed.  But as a novice I have a question:  In your original version, you had to refer to a directory where the stylesheets (o r image directories?) were located.  My directories are as follows:

/img/.......

/src/css/......

Also I have multiple directories in /img/ to organize my images in different folders.

Does this latest version automatically find everything?  or do I need to specify where everything is?  I’m confused…

Are we looking for stylesheets or the image directories?

Also, I placed the following script in the index page, but do I need to place this script in every page I create?

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

Is it that easy?  Download “jquery-1.2.6.min.js” and “preloadCssImages.jQuery_v4.js” and place the “$.preloadCssImages();” in the index page?  I’m done?

Sorry for so many questions....

Erik

Comment by Erik on 10/28  at  08:01 PM

Is there a problem running mootools scripts along with jQuery?  My mootools fx.slide script would not work unless I placed all the jQuery scripts ABOVE the mootools scripts in the <head> section.

<link rel="shortcut icon” type="image/ico" href="/img/icon/favicon.ico" />
<link rel="stylesheet" type="text/css" href="/src/css/main.css" title="default" />

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

</head>

Comment by Erik on 10/28  at  08:26 PM

@Erik: as for image paths, it’ll figure that stuff out on its own. The only options it accepts are for showing a visible progress indicator, which is not something most people will need with this script. Just put that function call somewhere in your javascript, whether it’s attached through an external JS file, or in the head of your page. It’ll do the rest for you.

As for mootools, you should check out the jQuery site for info about using jQuery site with other javascript libraries. Also, grab the latest source file above, as it avoids use of the $ variable, using “jQuery” instead. Which will also help with this.

Comment by Scott (Filament) on 10/31  at  12:51 PM

@everyone: As noted by @alexander above, he contributed a major bug fix to this script, and we’ve updated our source with his changes.

Notable improvements include:
- better browser support (bug fixes in IE and Opera)
- Major performance improvements, runs much much faster!
- New option to limit the number of simultaneous HTTP requests.
- Error handling
- overall code organization and cleanup

Thanks a lot @alexander! Please drop us a URL so we can credit your work properly!

Comment by Scott (Filament) on 10/31  at  03:50 PM

Thanks for the response, but I have one more question:  I cannot resolve the conflict between mootools and jquery.

Do I need to call this script on every page?

Is it possible redirect after the script is loaded?

Erik

Comment by Erik on 10/31  at  04:23 PM

@Erik

jQuery has a special format for other javascript libraries conflicting with it. It’s documented at
http://docs.jquery.com/Using_jQuery_with_Other_Libraries.

Instead of using:

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

You replace all of the $ instances:

// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery.preloadCssImages();
});

And there is the option to shorthand type it as well:

var $j = jQuery;
$j(document).ready(function(){
$j.preloadCssImages();
});

I can’t possibly test to see if this works on your script, but give it a go smile

Comment by Jarryd on 11/12  at  07:35 PM

Now you need to take a page from Google Web Tool Kit and BUNDLE those images into one file, to make it download fast, and then break them back out to the original files in the browser cache.

Comment by Ken G on 11/13  at  08:34 AM

Nice script, it works like a charme for me. But I have a question: How can I display the progress bar while loading the images and make it disappear after loading is complete (perhaps like the Lightbox-style by making the screen dark and focus on the progress bar at the center)? Because for me it makes no sense to display the progress bar all the time even when loading has completed. Unfortunately I am not a js-expert and don’t know how to realize this, so I would appreciate any help!

Kind regards,
Olli

Comment by Olli on 11/18  at  02:52 PM

Is there a cross-domain issue with parsing the CSS files? I get this error: Security error” code: “1000
if(sheets[sheetIndex].cssRules || sheets[sheetIndex].rules){

Our CSS and JS files are served from a separate server that lives on another domain…

Comment by Fontaine on 11/19  at  12:51 AM

Hoi ik ben het helemaal mee eens http://www.wereldvanproducten.com

Comment by Joshared on 11/23  at  08:40 AM

@Olli

I want to perform the same kind of task of you, since I’m loading a large background image and don’t want the user to see the page whilst this is loading. Have you managed to figure out a way to do this? Perhaps there is some kind of event that JQuery triggers when all of the images are loaded?

@Scott
Great plug-in! Only just got into JQuery in the past couple of days really impressed by it, especially the plug-ins. Please keep up the good work!

Comment by Richard on 11/25  at  05:40 AM

@Olli
After a little research, I think that just firing this event, which is triggered once all of the images have loaded, should do what you’re after:

$(window).load(function () {
$(’#loadInfo’).fadeOut(’slow’);
});

That also makes the loading window fadeout, which just means it’s now a matter of changing the CSS.

Cheers,
Richard

Comment by Richard on 11/25  at  07:21 AM

Hi!

The script doesn’t work via HTTPS. This should be quite easily fixable, from what I can see.

Regards,
Jaka

Comment by Jaka Jancar on 11/25  at  08:17 PM

Thanks for the great script!

Comment by anon on 11/28  at  08:22 AM

First of all, thank you for this wonderful tool. I wanted to find out if it is possible to have this script also preload images found in “img” tags in your XHTML?

Thank you again.

Comment by dangdang on 12/06  at  10:32 AM

I’ve got it downloaded. Thanks.

Comment by Rahul on 12/10  at  12:29 PM

I have use it on my site (wpesp.com). Thanks!!

Comment by Víctor on 12/17  at  05:10 AM

This is a wonderful idea. Many thanks for developing this and making it available. I’ve tried using this on our site—which has heavy css bkg img usage. However, I’m seeing a pretty big performance hit in that the images don’t appear to get cached, i.e., each page seems to reload all of the images from scratch rather than checking to see if they’ve already been loaded into the browser. Is there a workaround for this or is my browser (FF3) not behaving?

Comment by Brian on 12/24  at  01:40 PM

Ok, here is my problem - I like the first version where I could pass a directory to the preloader. I need to use this script in conjunction with an Expression Engine site in order to preload content in the dynamically created galleries, and loading the contents of a folder is really the only way to do that task. Is there any way to add this feature back in to the current version? Thanks for a great tool!

Jason

Comment by Jason L on 12/25  at  02:41 AM

In Firebug (FF 3.0.5) I am receiving the following error:

A parameter or an operation is not supported by the underlying object” code: “15
http://www.mydomain.com/js/preloadCssImages.jQuery_v5.js
Line 88

It is also interfering with some jQuery AJAX stuff - when I remove your plug-in and function call these problems disappear.

Cheers.

Comment by Jez on 01/11  at  11:52 AM

Security error” code: “1000
at Line 37

if(sheets.cssRules){//w3

Comment by feroz on 01/18  at  11:51 PM

For those mentioning security errors in Firebug, please check if the error occurs on a web URL. We can only replicate this issue when running locally.

Comment by Scott (Filament) on 01/19  at  12:47 PM

If you’re looking to preload content images (HTML img elements), you don’t need this plugin. You can do that easily in regular javascript by creating an array of your image file paths and iterating through them to create new image objects. Something like…

var myImages = [ ‘a.jpg’, ‘b.gif’, ‘c.png’];

for(var i=0; i<myImages.length; i++){
var img = new Image();
img.src = myImages;
};

Comment by Scott (Filament) on 01/19  at  12:56 PM

Great idea, and nice script!

May I make just a couple suggestions for your next release?

1. In line 107, the RegExp should also account for single-quote characters, which are valid CSS quote characters.  Also, you do not need to escape the “(” within the RegExp.  Finally, if you’d like, you can add a simple look-ahead to be sure you’re really a the end of a legitimate image file name. So the final RegExp would be:  /[^(“‘]+\.(gif|jpg|jpeg|png)(?=\W)/g The (?=\W) can be removed if you don’t want the look-ahead, but I doubt it would add more than a millisecond to the execution speed.

2. You may want to consider changing cssPile to an array (instead of a string), and using a join in line 107 like so:

var tmpImage = cssPile.join("").match(…

That should improve execution speed in IE6 and IE7 for CSS files with a lot of images.

-Todd

Comment by Speednet on 01/28  at  11:49 AM

I get the same error as Jez…

A parameter or an operation is not supported by the underlying object” code: “15
http://www.mydomain.com/js/preloadCssImages.jQuery_v5.js
Line 88

It sadly renders the script useless. I am sure it si a small problem, but I am too deep into a deadline to look for it right now (sorry!).

Comment by Soulhuntre on 01/30  at  01:16 PM

Apologies for not getting back sooner. I can confirm that the Firebug error also happens on a web URL. I have disabled the plug-in, but if you want to see the site for any reason it is at http://www.quoteseek.info

Comment by Jez on 01/30  at  03:17 PM

No worries Jez, it’s all cool.

I had to disable it as well.. I will probably wind up collecting all the image paths and doing a manual preload since this script is fragile. Too bad, cause it really is a great tool when it works!

Ken

Comment by Soulhuntre on 01/30  at  03:22 PM

I got also the “A parameter or an operation is not supported by the underlying object” code: “15
http://www.mydomain.com/js/preloadCssImages.jQuery_v5.js
Line 88 “ error in firebug. After searching a while I found this site: http://code.google.com/p/slideshow/wiki/FAQ#Why_won&#x27;t_Slideshow_work_with_Google_Maps?
There they have exactly the same error, the solution they got is placing the css file before the javascript file.

I tried this solution and it works for me! I simply placed the link to my css file before including the js files and I no longer see any errors.

Comment by Niels on 01/30  at  06:03 PM

Thanks Niels!
If everyone who was having issues could test that out, we’d appreciate knowing if that was the culprit.

Out of curiosity, are those who see this problem using jQuery 1.3? This may have been introduced now that jQuery no longer guarantees all CSS is loaded at domready. I’ll have to check on that.

In general, it’s probably a good idea to have your css linked before jQuery anyway, since you’ll want to try to get your CSS loaded before trying to get element dimensions, etc.

Comment by Scott (Filament) on 01/30  at  06:24 PM

Excellent, thanks a lot Niels - everything working OK now (and obviously thanks to Scott for the plug-in). Using 1.2.6. here.

Comment by Jez on 01/30  at  06:46 PM

Unfortunately, that didn’t fix the problem here. My CSS is loaded above my Jquery :(

Yes, I am running 1.3, and cannot regress to 1.2.6 for my project… however that DOES sound like it is a similar problem - it clearly seems like the CSS is not loaded by the time you guys get called. That would thus be the same problem as an ordering issue.

I wonder how I could force that?

Comment by Soulhuntre on 01/30  at  07:53 PM

@ Soulhuntre: try running this plugin onload instead of at domready.

$(window).load(function () {
$.preloadCssImages();
});

Comment by Scott (Filament) on 01/30  at  08:16 PM

Following the logic, I tried this in my ready function… ignore the try / catch as that was to guard against the error, but I wanted to see it this time. What I am doing is hoping to wait till AFTER the page loads to start caching.

$(window).load(function () {
$.preloadCssImages();
/* try { $.preloadCssImages(); } catch(e) {} */
});

Now I get a different error…

The firebug error is..

Security error” code: “1000
[Break on this error] if(sheets[sheetIndex].cssRules || sheets[sheetIndex].rules){

The raw error from the error console is..

Error: [Exception… “Security error” code: “1000” nsresult: “0x805303e8 (NS_ERROR_DOM_SECURITY_ERR)” location: “http://localhost:38754/example/support/js/preloadCssImages.jQuery_v5.js Line: 88"]
Source File: http://localhost:38754/example/support/js/preloadCssImages.jQuery_v5.js
Line: 88

Comment by Soulhuntre on 01/30  at  08:18 PM

Doesn’t this support URLS? for example,

files.blah.com/css/blah.css

because I tried it and it doesn’t work but when I do,

files/css/blah.css it works fine, is it a bug?

Comment by jono on 01/31  at  07:35 PM

Unfortunately, it looks like this bug will disqualify this plugin from use in our project :(

Thanks for all the effort that went into it and I hope eventually it gets fixed because it is a much needed tool!

Comment by Soulhuntre on 02/04  at  03:48 AM

The “simplified demo” URL returns Page Not Found.

Comment by Adrian B on 02/04  at  09:06 AM

Thanks for this script . Very Usefull

Comment by Michael on 02/05  at  04:30 PM

The script is just great! Congrats! It’s inspiring to see all of your hard work. I have bookmarked your website.

Regards, Paul

Comment by Inchirieri masini on 02/09  at  07:34 PM

Any ideas for jQuery 1.3.1?

I tried to preload in $(window).load with no luck:

Security error” code: “1000
[Break on this error] if(sheets[sheetIndex].cssRules || sheets[sheetIndex].rules){

Comment by gustin on 02/10  at  07:52 PM

@gustin - Sorry, I don’t have any ideas on it :(

Unfortunately, this project looks like it is essentially abandoned so you might not find an answer.

Ken

Comment by Soulhuntre on 02/10  at  10:08 PM

Just to clarify, this project is definitely not abandoned - it works quite well in most situations we’ve come across. We just haven’t come up with a fix yet for the cases mentioned above, but we’re giving it some thought.

Once we find a fix, we’ll post an update.

We welcome any ideas that anyone might have in the meantime. Thanks!

Comment by Scott (Filament) on 02/11  at  04:40 PM

Hello. A found your script very usefull, but I need a Callback function for it. Are U going to add such func?

Regards,
UdarEC

Comment by UdarEC on 02/20  at  02:06 PM

Hi guys,

Brilliant idea! I’ve tried using your script on one of our clients websites (http://www.studiomoso.com.au/designs/prs/), and I am using Safari in order to test dependencies in the activity window.

The website uses large background images on each section, hence your script is exactly what we need. After loading your script on the homepage to load all background images within the site (via css). I have found that those same background images are loaded again once when those pages are viewed. I was under the assumption that once your script ran through the css it would cache any images found within the css. Have i implemented your script incorrectly?

Any advice would be much appreciated.

cheers,
Ritch

Comment by Ritchie Anesco on 02/26  at  12:54 AM

Would you mind posting the HTML for using this script with the progress bar/percentage progress? Also, could you demonstrate how to automatically redirect once the preloading has completed?

Comment by Will on 03/11  at  01:46 AM

I have the same problems that Ritch is having. Even though all the images do get preloaded by the script they get loaded again when they are “activated”. I’m doing different images as a rollover effect for a menu and when I mouse over the link the image is loaded again even though it’s already been preloaded.

Kindly, Marcus.

Comment by Marcus Dalgren on 03/17  at  05:21 AM

i’m getting the same - Receive “access is denied” on line 58

Any ideea why ? TKs

Comment by Inchirieri masini on 03/18  at  06:18 AM

I came across this script and am planning on using it for a client’s site. I’ve read some of the comments and was hoping you could post a list of the current bugs.

Thanks again

Comment by Andre on 03/19  at  07:20 PM

help

Comment by sanju on 03/27  at  09:33 AM

while parsing the CSS files I get this error: Security error” code: “1000
if(sheets[sheetIndex].cssRules || sheets[sheetIndex].rules){

I have notice another guy with the same problem.

Any idea why ?

Comment by Farmacii on 03/30  at  02:48 AM

To those asking about the security error sometimes seen when using this script: can you confirm that it exists when running on a web server? So far, we’ve only seen this in Firefox with local file:// urls.

Comment by Scott (Filament) on 04/01  at  11:11 AM

Super script! 10x!

Comment by Tavy on 04/03  at  03:34 AM

I came accross this article searching on google how to preload images using jQuery. This article describes how to preload css images. But if you need to preaload normal images using jQuery read this detailed article.

Comment by JQuery Howto on 04/06  at  08:33 AM

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

has anyone tried manipulating this code

Comment by loan modification on 04/14  at  10:23 PM

How can I call a function AFTER all of the images are pre-loaded?

Like a callback function?? I think thats what I need

Comment by brainfog0 on 04/21  at  11:14 AM

Wow, indeed a great script. I think that this idea of preloading everything in the CSS is brilliant since you can have a plain text document for spiders, and a fully functional site for users.

Comment by Inchirieri Masini on 04/24  at  03:58 PM

This solution works for all browsers EXCEPT IE7 (I assume I can include IE6 and 8 though I have not tested in them). I am getting an error upon logging in to the app I developed:

Microsoft JScript runtime error: ‘jQuery’ is undefined

How can this be fixed?

The environment I am developing in is ASP.net 3.5 with VB, if that helps to clarify things. I thought I noticed that this site which I am posting this on is PHP. If so that might be the issue at which point I will abandon this code now and find something more suitable. No offense, because this actually is effective in PC browser’s Safari, FF and Opera. Just not in confounded IE.

Comment by jon on 04/27  at  03:39 PM

@jon: Hmm… I know we tested this script on IE6 and 7 before posting. Can you confirm our demos show this error for you as well? It sounds like a problem with IE getting your jQuery file properly loaded. I’m just guessing, but perhaps the content-type of your jQuery library file isn’t properly defined as “text/javascript\” for IE..?

Comment by Scott (Filament) on 04/27  at  03:51 PM

If you send contact me via email I could send a screenshot of the error which is happeninig in Visual Studio. It happens each time I click a link, but it still goes to another page and continues if I choose to “continue”. Either way I am leaving work and will be back here tomorrow to check in. Have a good one.

Comment by jon on 04/27  at  04:17 PM

I can confirm “security error: 1000” on a web server. bummer.

Comment by rene on 05/08  at  03:19 AM

btw (see my comment above): this happens on IE8/Vista, FF3/Vista and there are other jQuery plugins loaded (scrollto and supersleight) that work flawlessly. These are not the cause for this error, I’ve already tried without them. Result’s the same.

Comment by rene on 05/08  at  03:48 AM

Hi, i am interested in using this script, but for a blog, just i don´t understand where especify the url of my images, and how to put in the body onLoad, because the blog works different that html, and i don´t know so much java, if anyone could help me, i would be very grateful, see you…

Comment by proteo on 05/21  at  08:41 AM

Hey guys,

To fix the ‘security error 1000’ issue, and probably other problems, do this:
Under this line:

var csshref = (sheets[sheetIndex].href) ? sheets[sheetIndex].href : ‘[removed].href’;

Put this:

if (csshref.match(/^https?:\/\//)) continue;

This will avoid the security error that comes up when JS tries to access a remote CSS file.

Comment by Adam LeVasseur-Arribas on 06/02  at  01:46 PM

what if the specific page with preloading script does not use all the images referenced in CSS?.. they will be preloaded anyway, right?

Comment by bony on 06/18  at  03:48 PM

have to try it first

Comment by inchirieri auto on 06/21  at  04:47 PM

Hey, is there any way to know when the images are 100% done loading? A callback?

Comment by Jens on 06/25  at  04:56 AM

@Jens: Yes, you can use the load event for that.

$(window).load(function () {
// run code
});

Comment by Scott (Filament) on 06/25  at  09:30 AM

@Scott Thanks!

Comment by Jens on 06/25  at  09:44 AM

Hi, here is my approach, this is not for preloading css images but hope it helps.

It was the only think that actually worked for me when using jquery-1.3.2 and carousel.js (http://interface.eyecon.ro/docs/carousel) that was failing in FF3 and Safari4 on both winxp and osx when the images where not fully loaded.


var imgnum = 0;
var imgldd = 0;
$(document).ready(function(){
imgnum = $(’#carousel img’).length;
$(’#carousel img’).load(function(){
imgldd++;
if(imgnum == imgldd){
$(’#cargando’).css(’visibility’, ‘hidden’);
$(’#carousel img’).css(’visibility’, ‘visible’);
$(’#carousel’).Carousel(
{
itemWidth: 160,
itemHeight: 110,
itemMinWidth: 160,
items: ‘a’,
reflections: 0,
rotationSpeed: 1.8
}
);
}
});
});

Comment by supermegapollo on 06/26  at  02:54 PM

This doesn’t seem to be working for me. Firebug doesn’t output any errors… I wanted to get this working so I could swap out background images with jQuery. The swapping and everything works fine, its just not preloading my images. It says that it parses your css files, so I put this in my main css file:

background-image: url("../img/enginefeatures.jpg");
background-image: url("../img/monsterfeatures.jpg");
background-image: url("../img/racingfeatures.jpg");
background-image: url("../img/mixomfeatures.jpg");

The last one is the one that gets loaded of course, but the other 3 don’t preload. I did it like that, so that it could get the URLs from the css file only. If you can suggest a better way of doing it, that’d be great. I didn’t know if this was a bug though, since my urls all start with ../. Thanks.

Comment by Blake on 06/29  at  10:15 PM

I’ve noticed this occasionally fails on Firefox 3.5 with the error log:

Error: uncaught exception: [Exception… “A parameter or an operation is not supported by the underlying object” code: “15” nsresult: “0x8053000f (NS_ERROR_DOM_INVALID_ACCESS_ERR)” location: “http://www.metoffice.gov.uk/lib/includes/javascript/preloadcssimgs.js Line: 88"]

This seems to happen much more frequently with the minimized version (same message but line 7). Also seems to occur more frequently with more ‘distant’ servers; very infrequent with my local test server.

Comment by JAH on 07/03  at  05:56 AM

Add a Comment:* required fields

Recently on Twitter...

Accessible, custom checkbox and radio inputs are easier than you think! Check out our new Filament Group lab post: http://bit.ly/ofNIX

@filamentgroup 1 day ago...