加载图像后重定向

编程入门 行业动态 更新时间:2024-10-10 21:26:14
本文介绍了加载图像后重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我最近开发了一个网站,问题是每个页面的背景都是图像,因此,在较慢的连接上(某些目标受众的情况),图像会逐渐加载。下载,解决这个问题我试图做一个预加载页面,执行以下操作:

So I have been recently developing a site, The problem is the backgrounds for each page are images, and as a result, on slower connections (which is the case of some of the target audience) the images load progressivly as they are downloaded, to resolve this I am trying to make a preloading page that does the following :

  • 加载图像
  • 加载完成后,将用户重定向到请求的页面

  • Loads the Images
  • Once the loading is done, redirects the user to the requested page

<script type="text/javascript"> <!--//--><![CDATA[//><!-- var images = new Array() var count=0; function preload() { for (i = 0; i < preload.arguments.length; i++) { images[i] = new Image() images[i].src = preload.arguments[i] } if(count==4) { window.location = "index.html"; } } preload( "backgrounds/bg1.jpg", "backgrounds/bg2.jpg", "backgrounds/bg3.jpg", "backgrounds/bg4.jpg" ) //--><!]]>

问题是它直接重定向(我假设它只是开始下载图像然后直接将一个添加到计数器变量,快速达到4并且不给图像下载时间。

The problem is it redirects directly (I assume that it just starts the download of the image then directly adds one to the counter variable, quickly reaching 4 and not giving the image the time to download.

任何想法如何让我在图像下载完成时发出信号,或者只在下载图像后执行重定向?

Any ideas how I can either make it signal me when the images have finished downloading, or only execute the redirect after it has done downloading the images ?

推荐答案

你需要等待加载事件。这很简单:

You need to wait for the load event. It's quite simple:

function preload(images, timeout, cb) { var cbFired = false, remaining = images.length, timer = null; function imageDone() { remaining--; if(remaining === 0 && !cbFired) { cbFired = true; clearTimeout(timer); cb(); } } function timerExpired() { if(cbFired) return; cbFired = true; cb(); } for(var i = 0; i < images.length; i++) { var img = new Image(); img.onload = imageDone; img.onerror = imageDone; img.src = images[i]; } timer = setTimeout(timerExpired, timeout); }

您需要检查一些内容,以免用户卡住:

You need to check a few things so that users don't get stuck:

  • 你需要等待加载和错误以便在图片无法加载时页面不会卡住。
  • 您应设置最大超时。
  • 另外,在你的代码中, i 是一个全局变量(没有 var 声明)。
  • You need to wait for both load and error so that the page doesn't get stuck if an image fails to load.
  • You should set a maximum timeout.
  • Also, in your code, i was a global variable (no var declaration).

以下是如何使用它:

var images = [ "backgrounds/bg1.jpg", "backgrounds/bg2.jpg", "backgrounds/bg3.jpg", "backgrounds/bg4.jpg"]; preload(images, 10000 /* 10s */, function () { window.location = 'next_page'; });

更多推荐

加载图像后重定向

本文发布于:2023-10-12 05:09:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483801.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重定向   图像   加载

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!