user5660692
user5660692

Reputation:

How to prevent some background-images caching

adding some random number it works, but only for img

<img src="example.jpg?377489229" />

Is there any way to prevent caching prp. background-image?

<div style="background-image: url(example.jpg  )"></div>"

Upvotes: 3

Views: 6812

Answers (2)

num8er
num8er

Reputation: 19372

To generate image urls with dynamic timestamp as query param You need at least JavaScript code that will dynamically add latest timestamp to background image url and make something like this:

someimage.jpg? (new Date()).getTime()    =>   someimage.jpg?1479341018085



You can use this example:

function getNoCacheBgElements() {
  return document.querySelectorAll('.no-cache-bg');
}

function loadBgImageForElement(element) {
  element.style['background-image'] = 
    'url('+ element.attributes['data-background-image'].value + '?' + (new Date()).getTime() +')';
}

function loadBgImages() {
  for(
    var i = 0, elements = getNoCacheBgElements();
    i < elements.length;
    loadBgImageForElement(elements[i]), i++ 
  );
}

window.onload = function() {
  loadBgImages();
};
.size-100x100 {
  min-width: 100px;
  min-height: 100px;
}
   
.float-left {float: left;}
.margin-10 {margin: 10px;}
<p> These background images loaded dynamically every time You hit "Run code snippet". </p>

<div class="no-cache-bg size-100x100 float-left margin-10" data-background-image="http://lorempixel.com/output/abstract-q-c-640-480-8.jpg"></div>

<div class="no-cache-bg size-100x100 float-left margin-10" data-background-image="http://lorempixel.com/output/abstract-q-c-640-480-9.jpg"></div>

<div class="no-cache-bg size-100x100 float-left margin-10" data-background-image="http://lorempixel.com/output/abstract-q-c-640-480-10.jpg"></div>
 
</br>
<p> Check browser's network tab and You'll see that it requests for images on every page load. </p>

Upvotes: 2

alex
alex

Reputation: 490423

The same technique will work there.

<div style="background-image: url(example.jpg?377489229)"></div>

Assuming your server doesn't act differently with the presence of that GET param.

This will only break the cache once though, if you want it to always hit the server, you will need to use some different techniques.

Upvotes: 5

Related Questions