Gif reset caching without hard refresh

Viewed 226

I need to place separate gifs in multiple tab sections. Because I click through tabs which reveal each gif and tabs out of another, I require Javascript to reset the gif on a event handler. The script for this section works fine. I have written a resetGif function to correspond with this. This also works for the most part. The issue I'm finding with this particular script is that the reset is caching at some point. If I perform a hard refresh in browser the resetGif script performs correctly. If I perform a regular refresh, the resetGif script, runs only once.

I am not overly experienced with Javascript, so I have been unsure what to try next.

// Function resets gif through id

function resetGif(id) {
    var img = document.getElementById(id);
    var imageUrl = img.src;
    img.src = "";
    img.src = imageUrl;
}

I need the resetGif function to run/reset gif every-time it is being called regardless of whether I have hard refreshed or normal refresh. I need it to not cache.

2 Answers

If you want to force a reload of the image, append a timestamp to the src so it's unique, like this:

function resetGif(id) {
  var img = document.getElementById(id);
  var imageUrl = img.src;
  img.src = '';
  img.src = imageUrl.split('?')[0] + '?' + new Date().getTime();
}

Note that, in theory, the line setting src = '' should not be needed, unless there's some odd browser behaviour I'm not aware of.

function resetGif(id) {
  var img = document.getElementById(id);
  var randomString = Math.random().toString().split(".")[1];
  var imageUrl = img.src;
  img.src = ''; // will remove image source 
  img.src = imageUrl.split('?')[0] + '?' + randomString;
}

By generating a random string, you can force a reload of the image. and every time it is unique so I think this error will be solved.

Related