Javascript to only display animated gif when loaded

后端 未结 3 663
后悔当初
后悔当初 2020-12-11 11:36

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

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 11:53

    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:

    
    

    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.

提交回复
热议问题