Question

I got a quick question about sprites in css: Will I send two HTTP Request if I include the same image twice in a css file? For example if I want to load two different buttons from the same icon set image:

.btn-1 {
    background:url('img/icons.png') 0 0;
}

.btn-2 {
    background:url('img/icons.png') 0 -60px;
}

or is there another way to only include the image once?

Was it helpful?

Solution

The browser will cache the image so the 2nd time its fetched from cache.

But what you want to do in a situation like this is to let CSS do its job.
If those buttons are <a> for example.

a {
    background: url('img/icons.png');
}

.btn-1 {
    background-position:0 0;
}

.btn-2 {
    background-position: 0 -60px;
}

OTHER TIPS

Besides that what Ólafur said, you could also rewrite your CSS that the URI reference will only occur once:

.btn-1,
.btn-2 {
    background:url('img/icons.png') 0 0;
}
.btn-2 {
    background-position: 0 -60px;
}

Yes but the client should receive a HTTP 304

304 Not Modified If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.

So the image will not be send twice but used from cache instead.

HTTP/1.1: Status Code Definitions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top