Css - change image frequently with less server requests

I have html. Its content is described in css. With different functions, the class name of the div changes to imageholder1,2 etc.

.imageholder1 {      content: url('image1.png')}
.imageholder2 {      content: url('image2.png')}


But I think this is causing multiple server requests every time the class name changes.

Is there a way to reduce server requests for the image file. I would like to store the image in a variable and then specify it from the css code. Is it possible?

I also tried using a css-shaped sprite, but I would need a more flexible way.


source to share

3 answers

If you put all your images in a hidden (display none) div, they will load immediately. The browser has to cache them, so every time it changes it is fetched from the client system.

<div style="display: none;">
  <img src="image1.jpg">
  <img src="image2.jpg">
  <img src="image3.jpg">




Preload the images and they will cache the images and only ask for each image once (this will also allow smooth transitions between images since subsequent images will already be loaded). This will limit your HTTP requests to one request per image (the minimum you can achieve without sprite sheets).

Here's a really nice jQuery solution (which doesn't add hidden elements to the DOM), but really any preloading scheme should work:

$.preloadImages = function() {
  for (var i = 0; i < arguments.length; i++) {
    $("<img />").attr("src", arguments[i]);






In my opinion, if we load multiple images on the page, it will have multiple requests. Instead, just use a sprite that combines all the images. This will display one image from the server. Then define background css properties for such classes so that they have different sprite position values ​​causing the desired image to be displayed.

.imageholder1 {
  background: url(/path/to/sprite.png) -60px -120px no-repeat;

.imageholder2 {
  background: url(/path/to/sprite.png) -20px -120px no-repeat;




All Articles