Skip to content Skip to sidebar Skip to footer

Reloading Animated .gif In Explorer Doesn't Work With Img.src=""

Im running a loop of different animation sequences and at some point I want to add a GIF animation. Appending the GIF to a div works fine the first time, however in my second loop

Solution 1:

How about reloading the gif, but preloading it for the next time you want to show it ? Then you wouldn't have to wait on reloading... but you would still destroy the bandwidth if you have big images and reload them often, could be bad especially on mobile devices.

Maybe you should use this script only for IE. Anyway, this works on the IE11 I run in my virtual machine, I can't really test many more.

Basically, you have image objects, to whose URL you append random and/or increasing values, in order to force reloading. When you toggle, you replace the element that is in the div with the other one. Then you replace the removed item by preloading the image with a new copy of the same image but different randomized url.

Here's a typical snippet of code with a random gif on the internet that plays only once. Clicking "toggle" restarts the gif, even on IE.

var imgUrl = "http://i.imgur.com/oZqny.gif"
var myDiv = document.getElementById("zou");
myDiv.style.display = "block";
var loopCount = 1;

// against caching : load= between page loads, loop= between clicks on "toggle"
imgUrl += "?load=" + new Date().getTime() + "&loop=";
var imgs = [new Image(), new Image()];
imgs[0].src = imgUrl + (loopCount - 1);
imgs[1].src = imgUrl + loopCount;

function toggleGifAnimation() {
  if (loopCount == 1) {
    myDiv.appendChild(imgs[loopCount % 2]);
  } else {
    myDiv.replaceChild(imgs[loopCount % 2], imgs[(loopCount + 1) % 2]);
  }
  loopCount++;
  imgs[loopCount % 2] = new Image();
  imgs[loopCount % 2].src = imgUrl + loopCount;
}

document.getElementById("zde").onclick = toggleGifAnimation;
<button id="zde">toggle !</button>
<div id="zou">
</div>

Solution 2:

...
tmpImgUrl = tmpImgUrl + "?random=" + Math.random().toString();
imgContainer.src = tmpImgUrl; 
...

The script will ask the server to deliver the image with url http://... /assets/myGIFanimation.gif?random=0.37928739409283748


Post a Comment for "Reloading Animated .gif In Explorer Doesn't Work With Img.src="""