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

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

问题描述

我的网站上有一个大约 2MB 的动画 gif 横幅.对于连接速度较慢的人,我想包含一些 Javascript,它只会在 gif 完全加载时显示(并开始播放),以便网站的其余部分在 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 对象来执行此操作,就像这样(当您想开始加载横幅时执行此操作,可能在 <代码>加载):

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天全站免登陆