Javascript to only display animated gif when loaded

RLJ picture RLJ · Apr 29, 2011 · Viewed 10.2k times · Source

I have an animated gif banner on my website that is around 2MB. For people with slow connections, I want to include some Javascript that will only display (and start playing) this gif when it is fully loaded, so that the rest of the website will already display whilst the gif is still loading. Ideally, I would have one image (loading.gif) be displayed first, and then switched to the banner (banner.gif) with javascript when banner.gif is loaded.

How do I do this? (I'm new to Javascript)

Thanks!

Answer

Ry- picture Ry- · Apr 29, 2011

You can do this using an Image object, like so (do this when you want to start loading the banner, probably in onload):

var banner = new Image();
var loading = new Image();
var bannerElement = document.getElementById("banner"); // assumes an element with id "banner" contains the banner image - you can get the element however you want.
banner.src = "location/of/the/image.gif";
loading.src = "loading.gif";
banner.onload = function() {
     bannerElement.removeChild(bannerElement.lastChild);
     bannerElement.appendChild(banner);
};
bannerElement.removeChild(bannerElement.lastChild);
bannerElement.appendChild(loading);

Your banner element should look like this:

<div id="banner"><img src="location/of/the/image.gif" alt="Banner" /></div>

This is so that 1) The bannerElement.removeChild part will work and 2) To keep with the principles of progressive enhancement so people without JavaScript aren't left out.