Restart an animated GIF from JavaScript without reloading the image
Next answer works only if your .gif
image is located on your server or severs that provide Access-Control-Allow-Origin: *
header in response, due to Cross-Origin limitation.
I use built-in fetch()
to download gif to memory blob. Then this blob is used to update .src
attribute of img element whenever you need to restart animation. As blob is kept in-memory it is not re-downloaded. Also to restart animation you just need to update .src
attribute with same value again.
If fetch()
is not supported by target browser then good-old XMLHttpRequest
may be used. Also URL.createObjectURL()
may be named differently then wrapper like here can be used.
Code below may also be tested on jsfiddle.
<input id="btn" type="button" value="ReStart">
<img id="img" height="150">
<script>
document.addEventListener('DOMContentLoaded', ()=>{
// fetch works only with urls on same server or servers that provide header "Access-Control-Allow-Origin".
fetch('https://api-project-268277679120.appspot.com/h80bm5vc4iw7?url=https://i.stack.imgur.com/SkGeh.gif')
.then(r=>r.blob())
.then(b=>URL.createObjectURL(b))
.then(u=>{
document.getElementById('img').src = u;
document.getElementById('btn').onclick = ()=>{
document.getElementById('img').src = u;
};
});
});
</script>
You should preload your images into code.
var image = new Image();
image.src = "path";
when you want to use:
nextimg_img.attr('src', image.src);
Then when you swap the src out just swap from the preloaded image objects. That should do the trick to avoid redownloading.