Preloading CSS Hover Images

DEPRECATED: This post has been marked as deprecated and may no longer 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 is the author of Advanced Microservices and is a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.