Javascript只在加载时显示动画gif [英] Javascript to only display animated gif when loaded

查看:336
本文介绍了Javascript只在加载时显示动画gif的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一个动画gif横幅,大约2MB。对于连接速度慢的人,我想要包含一些只在完全加载时显示(并开始播放)此gif的Javascript,以便在gif仍在加载时已经显示网站的其余部分。理想情况下,我会首先显示一个图像(loading.gif),然后在加载banner.gif时使用javascript切换到横幅(banner.gif)。

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.

我该怎么做? (我是Javascript的新手)

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

谢谢!

推荐答案

您可以使用 Image 对象执行此操作(当您要开始加载横幅时执行此操作,可能在 onload ):

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>

这样:1)bannerElement.removeChild部分将起作用2)遵守原则渐进式增强,所以没有JavaScript的人不会被遗漏。

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.

这篇关于Javascript只在加载时显示动画gif的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆