There is an alternative that does not reload the GIF every time and waste bandwidth.
It involves storing the GIF as Base64 in memory (circumventing browser cache), and uses the FileReader API (which seems to be supported in all modern browsers). Note that loading images this way is subject to cross-origin policy (unlike the image reload solutions.)
Update: Browser caching is getting smarter about caching background image data URI's, causing the animation not to start over. I found I had to add a cache-busting random string to the data url now (which according to the DataURI Scheme, should be considered an optional attribute. Tested in Chrome & IE Edge.)
See it in action: http://jsfiddle.net/jcward/nknLrtzL/10/
Here's how it works. This function loads the image as a Base64-encoded string.
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob'; // IE11, set responseType must come after .open()
xhr.send();
}
Then, any time you want to restart the GIF animation, change the background-image
property to none
, then the base64 string (in some browsers, you need to re-add the child to trigger the update without a setTimeout):
$div.css({backgroundImage: "none"});
$div.parent().add($div); // Some browsers need this to restart the anim
// Slip in a cache busting random number to the data URI attributes
$div.css({backgroundImage: "url("+img_base64.replace("image/gif","image/gif;rnd="+Math.random())+")"});
Thanks to this answer for the toDataURL
function (with fix for IE11.)