简体   繁体   中英

How do I get a div to grab it's background image from the internet instead of from the cache?

Relevant Javascript being run once every fifteen minutes to get the relevant image off the internet:

document.getElementById('weatherbug').style.background = "url('http://tinyurl.com/jwltx5s') repeat scroll -1px -24px transparent";

Relevant HTML this is linked to:

<DIV ID='weatherbug'></DIV>

Other HTML I've used to try and keep this from using the cache:

<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
<META HTTP-EQUIV="Pragma-directive: no-cache">
<META HTTP-EQUIV="Cache-directive: no-cache">

Results: The image refreshes itself from the cache regardless, ignoring changes in the source image, which changes roughly once per hour. If there is not internet access, this results in a blank image (good behavior) unless there's a copy in cache, in which case an old image is shown (bad behavior). Also, if there is a copy in the cache, the newly updated image on the internet is not shown (bad behavior).

Other tricks I have tried: I've attempted to alter my javascript to add a randomizing element on the back end of the address, to force the cache's contents to be invalidated with each invocation, but altering the address by adding a ?randomnumberherebasedofftheDateObject on the ass end of the address breaks both the original link to the image and the tinyurl version since neither end in a proper .gif suffix.

How can I force the cache to NOT save this image, or at least to invalidate it after a decent time interval so a new download from the relevant server is required to display the information? Frankly I'm stumped. :(

  • Aaron Nichols

I'm not sure where your difficulties are. Cache busting is the way to go.

The first thing is you shouldn't be using the url shortener. Just access the end url directly.

All you need to do is add a cache busting parameter and a random value to the end of each url request.

I've setup a codepen that demonstrates this. It gets the updated image every 2 seconds. Monitor the image requests in dev tools and you can see the images are not being cached.

http://codepen.io/anon/pen/EayVJO

window.addEventListener('load', function () {
  var url = 'http://weathersticker.wunderground.com/weathersticker/cgi-bin/banner/ban/wxBanner?bannertype=wu_simplewhite&airportcode=KTTN&ForcedCity=Princeton&ForcedState=NJ&zip=08540&language=EN';

  var weatherbug = document.querySelector('#weatherbug');
  setInterval(function () {
    var rand = Math.floor(Date.now() * Math.random());
    weatherbug.style.background = 'url(' + url + '&qqq=' + rand + ') center center no-repeat';
  }, 2000);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM