How to prevent some background-images caching

青春壹個敷衍的年華 提交于 2019-12-13 16:31:50

问题


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>"

回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/39366225/how-to-prevent-some-background-images-caching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!