Redirect after loading images

家住魔仙堡 提交于 2019-12-02 06:24:36

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:

  • 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).

Here's how to use it:

var images = [ "backgrounds/bg1.jpg",
    "backgrounds/bg2.jpg",
    "backgrounds/bg3.jpg",
    "backgrounds/bg4.jpg"];

preload(images, 10000 /* 10s */, function () {
  window.location = 'next_page';
});

Modify your preloader so that it binds to the "onload" event of the Image object and when all callbacks are fired it redirects (untested sample code below):

var images = new Array()
var count = 0;
function preload() {
    var numImages = preload.arguments.length
    for (i = 0; i < numImages; i++) {
        images[i] = new Image();
        images[i].onload = doneLoading; // See function below.
        images[i].src = preload.arguments[i];
    }
    function doneLoading() {
        if (++count >= numImages) {
            window.location = "index.html";
        }
    }
}
preload(
    "backgrounds/bg1.jpg",
    "backgrounds/bg2.jpg",
    "backgrounds/bg3.jpg",
    "backgrounds/bg4.jpg"
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!