Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gifs, Javascript and Multiple Instances

Tags:

javascript

gif

Maybe a silly question but here goes anyway.

Example: Let's say I have one non-looping animated GIF and I have two img elements.

<img src="" id="slot1" />
<img src="" id="slot2" />

So I use a little javascript to change the source of the slot1.

function changE(x)
{var image=document.getElementById (x);
 image.src="animated.gif";
}

someButtonGotClicked=changE('slot1'); 

that works fine. Gif plays from start to end but if I then change the src of slot2 to the same gif:

changE('slot2');  

slot1 resets it's gif back to the start to sync with slot2 starting it's gif.

Now i'm aware I could copy the gif and have 2 seperate files to use and I know about sprite sheets but I'm curious If I can use one copy of a gif and have it used multiple times on a page without all instances of the gif being restarted everytime another img element recieves the same file as it's src?

Hope that wasn't confusing. Thanks.

like image 479
Nikki Avatar asked Feb 17 '12 22:02

Nikki


1 Answers

Once an image is loaded in memory, all other objects that request that image, using the same URL, get a reference to the image from the browser cache. This avoids loading the same image multiple times. In the case of a gif, one of the meta data to be kept track of is the current frame, which is stored not at the <img> dom element, but rather at the browser level in the structure it uses to store that gif.

On load, that frame index is reset. So, while the browser is processing the gif loop, a second image loading sets the current frame index to the beginning, hence both images synchronize.

This is a browser implementation, and it seems most browsers follow this implementation. One advantage to this is that if you have thousands of little gifs (from the same URL) in one page, the browser would do a lot less computation to render them, because it would only change one frame index, not thousands.

Edit: To fix your code you'd have to basically add something random at the end of your image.

function changE(x)
{var image=document.getElementById (x);
 image.src="animated.gif?" + Math.random();
}

So the browser thinks this is a different image (i.e. different URL).

like image 146
Candide Avatar answered Oct 07 '22 23:10

Candide