tags:

views:

284

answers:

5

When I include an image as an <img> tag as well as a background image on a DOM element, the browser sometimes makes two requests for the same image. This also sometimes happens when using the hover pseudo-property. For example:

<html>
<head>
<style>
    div{
        background: transparent url(/img/stuff.png) no-repeat;
    }
    div:hover{
        background: transparent url(/img/stuff.png) no-repeat 25px 0px;
    }
</style>
</head>
<body>
    <img alt="" src="/img/stuff.png"/>
    <div>
    </div>
</body>
</html>

Why would the image be requested twice (or possibly three times)? Is this a behavior I can avoid? If so how?

[EDIT]

I noticed this while watching the Google appengine local server process so I'm fairly certain it wasn't actually cached by the browser (As it could have been if I had seen it in firebug or webkit inspector).

I've seen this in Google Chrome, IE7, and Firefox 3.

A: 

It seems like this would be a browser caching issue to me.

You could try preloading it like:

<img alt="" src="/img/stuff.png" style="display: none;"/>

but I'm not sure if that would work or not.

Ryan Smith
I've found some browsers don't load images with display:none.
alex
+3  A: 

This is a known problem with IE6, is that the browser you're having problems with?

There are several causes and fixes listed here:

http://www.fivesevensix.com/studies/ie6flicker/

atetlaw
A: 

Answer depends on how you discovered that image requested more then once. Do you watching webserver logs or using something like Firebug on client-side? Try to post more details in your question.

Anyway, seems like browser should get image from cache.

dobrych
A: 

I have the same behavior. the image requested twice and it has two requests from server , one from the css file as a request referrer and the other from the aspx or htm file as request referrer. I tried this with firebug 1.5 and other HTTPparser programs.

mina amir
+1  A: 

I've seen similar behavior in my own large scale web applications that use a large amount of images. Even with JavaScript preloading, images are sometimes requested a second time (although I haven't watched closely enough to see if any were requested more than twice.

My conclusion was that the browser's cache may have been full and entropy may have kicked in, removing older items or those that are not currently being used. Try increasing your browser's maximum cache size and see if the behavior continues. Also, in Firefox, you can checkout about:cache.

Justin Johnson
Thanks Justin! I've never used about:cache, that seems like a great tool.
brad
Yar, I Just found that particular gem myself.
Justin Johnson