Thursday, April 13, 2006

IE will cache CSS background images, if you give it a chance

You're using the latest CSS background-image trickery to get lots of cool effects on your web pages. But when you load the pages up in IE, the images seem to flicker when you move the mouse around over them. You never noticed it before when developing on your local machine, but it's painfully apparent when operating over a slow connection. The reason for this is that Internet Explorer 6 takes a conservative approach to caching, that is: When in doubt, do not cache. But IE will in fact cache your CSS background images -- even when it is configured to Check for newer versions of stored pages [x] Automatically -- if you give it a chance. The trick is to configure the web server to properly set the cache-control header. In order for images to get cached in Automatic mode, IE needs to see an HTTP header like this in the response:
Cache-Control: max-age=86400
The number is the # of seconds to cache (24 hours in this case). If you're using a Java server like Tomcat you will not get cache-control automatically, but you can do it with a servlet filter. If you're using Apache httpd then you can just turn on a configuration directive. WARNING: If anything else on the server is setting the "no-cache" directive, then you may end up with a response header like this:
Cache-Control: max-age=86400, no-cache
That header says "cache me for 24 hours, but actually, don't cache me after all." So IE will panic and simply not cache it. To verify you're getting the right cache-control header, inspect the response headers using Fiddler Tool in IE (fiddlertool.com) or the livehttpheaders extension in Firefox.

3 comments:

Anonymous said...

Thankyou!!!

Michael said...

Found a site with a similar and simpler preloading css with a downloadable example at http://www.combsconsulting.com/image-preloading-through-css3-caching/index.html

Jeoff Wilks said...

This blog post is not about image preloading; it is about properly setting cache headers.

I'm uncertain about the credibility of a post that claims that Firefox uses Webkit (wrong), IE 8 uses a "verient" (sic) of Webkit (wrong), and shrugs off IE6 and IE7 support as unnecessary. (Not so fast, they still account for 35% of all web users.)

I hope you are not the same Michael who authored that post, because if so, it would be misleading to say that you "found a site" when referring to your own work.