I'm trying to make a gif restart when the user clicks on it, without having to reload it (my gif is too heavy for that, I actually preload it for my application). My current code works perfectly on Chrome and all "modern browsers", but I need that to work in IE11 as well, and that's where the struggle begins.
Here is a sample code, that works perfectly on Chrome but not on IE11:
function activate_gif(){
document.getElementById("img1").src = "https://i.imgur.com/Rsc0qOw.gif";
}
.myDiv{
width: 500px;
height: 300px;
}
.myDiv img{
width: 100%;
height: 100%;
}
<button onclick="activate_gif()">
Click me
</button>
<div class="myDiv">
<img id="img1" src="https://i.imgur.com/Rsc0qOw.gif">
</div>
You can also find it on this jsFiddle: https://jsfiddle.net/c6hodyh2/3/
You can find an other (not) working example of the problem (perfect with Chrome, not working with IE): https://codepen.io/InSightGraphics/pen/CAlci
What I've tried so far
Attempt 1
From this SO question, I tried the following JS code, to "force" the cache to refresh:
function activate_gif(){
document.getElementById("img1").src = "";
document.getElementById("img1").src = "https://i.imgur.com/Rsc0qOw.gif";
}
Result: No success, it had absolutely no different effect from my original code.
Attempt 2
From this article, I tried to refresh the innerHTML content:
function activate_gif(){
document.getElementById("img1").style.display = '';
document.getElementById("img1").innerHTML = document.getElementById("img1").innerHTML;
}
Result: No change in IE, and it stopped working in the other browsers, so I suppose it triggered a console error.
Attempt 3
From this SO question, I tried to use a simplified version of the solution, basically by forcing the image to be loaded again by adding a random suffix to its source URL:
function activate_gif(){
document.getElementById('myImg').src = 'mysrc.gif?' + Math.random();
}
Result: This reloads the gif, which solves the cache problem by itself. However, the gifs I use in my real-life application are too heavy, so if the image is to be downloaded everytime the user presses the button, it results in a poor user experience, especially for those with a weaker bandwidth.
Attempt 4
From @IStepashka's answer, I tried to first set a (random and found on the web) blank image before setting back my original source:
function activate_gif(){
document.getElementById("img1").src = "https://i.ytimg.com/vi/f3cLOucMpD0/maxresdefault.jpg";
document.getElementById("img1").src = "https://i.imgur.com/Rsc0qOw.gif";
}
Result: Same as attempt 1, it didn't change anything. My code is still working on Chrome, but not on IE.