Preloading CSS Hover Images

Support this website by purchasing prints of my photographs! Check them out here.
DEPRECATED: This post may no longer be relevant or contain industry best-practices.

Don't you hate it when your CSS buttons disappear for a moment when someone hovers over them for the first time? Of course you do. Here is a simple fix.

First you'll want to set up your pages to load the javascript file. I will name the file preload.js. This is the code that you will put in your webpages that you will want to have fixed:

<script language="javascript" src="preload.js" type="text/javascript"></script>

Now we set up the external file. The reason we put this stuff in an external file is to reduce loading times for each page. Here is the content (change filenames where applicable):

if (document.images) {
  pic1= new Image(198,34);
  pic2= new Image(198,34);
  pic3= new Image(198,34);
  pic4= new Image(198,34);
  pic5= new Image(198,34);

Each image requires two lines to get the job done as you can probably tell. The new Image function has two arguments; width and height. You do not have to specify the correct width and height, you can just set each to 1.

There is a much better technique to do this using pure CSS, however if you have already set the CSS in stone or don't want to combine all of your navigation images into one large image this method will do the job.

Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.