加载图像后重定向 [英] Redirect after loading images

查看:275
本文介绍了加载图像后重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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';
});

这篇关于加载图像后重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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