所以我最近开发了一个网站,问题是每个页面的背景都是图像,因此,在较慢的连接上(某些目标受众的情况),图像会逐渐加载。下载,解决这个问题我试图做一个预加载页面,执行以下操作:
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
问题是它直接重定向(我假设它只是开始下载图像然后直接将一个添加到计数器变量,快速达到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'; });更多推荐
加载图像后重定向
发布评论