【问题标题】:How to go about writing a Javascript pre-loader?如何编写 Javascript 预加载器?
【发布时间】:2011-05-04 01:38:53
【问题描述】:

我不是在谈论如何pre-load images using Javascript,我更多地考虑的是 Flash 预加载器,它会在 SWF 加载时显示某种反馈。

有问题的网站使用了大量的 Javascript,并且在页面加载时需要许多大图像,所以我希望将网站隐藏在加载屏幕后面,直到初始图像全部加载。

【问题讨论】:

  • 你应该在(惊喜!)Flash 中编写一个 Flash 预加载器 :)
  • @David 显然。但我不是在寻找 Flash 预加载器,我正在尝试用 JS 编写一个用于无 Flash 网站的预加载器。
  • 啊,我明白了。我很困惑。对不起。
  • @alex:我们做到了,而且看起来它绝对可以满足我们的需求,干得好!不过有一个问题,它是否也处理 CSS 背景图像等,还是仅处理 <img> 标签?
  • @Matthew 我刚刚推送了我的新版本,它支持 CSS 中的图像引用。让我知道你的想法:)

标签: javascript jquery html preloader


【解决方案1】:

我写了一个jQuery plugin called waitForImages 让你这样做。

回调允许您在每个图像加载后执行任何操作...

$('body').waitForImages(
function() {
   // Called when all images have loaded.
},
function(loaded, total, success) {
   // Called once each individual image has loaded.
   // `loaded` is the number of images loaded so far.
   // `total` is the total number of images to load.
   // `success` is `true` if the image loaded and `false` if the image failed to load.
   // `this` points to the native DOM `img` element.
},
// Set the third argument to `true` if you'd like the plugin to look in the CSS
// for references to images.
true
);

jsFiddle.

【讨论】:

    【解决方案2】:

    我第一次学习 JavaScript 时写过一个。我要试着在一秒钟内找到它。基本思想是在页面之外有一个隐藏元素,然后在其中加载您的图像。

    当我开始写这个时,当心,丑陋的代码。尽管有很好的 cmets,但它可能并不是您要寻找的。只需修改它并使其成为通用功能。基于 jQuery,用于 javascript 库:

    this.preload = function(){
        /*
         * Preloads all the image to a hidden div so the animation won't glitch.
         */
        if (document.getElementById("preload")){                // Checks for existance.
            var preload = document.getElementById("preload");   // Gets the preload div if it exists.
        } else {
            var preload = document.createElement("preload");    // Creates the preload div if it doesn't exist.
            $(preload).attr("id", "preload");
        }
        for (var i=0; i<this.aNodes.length; i++){               // Get all the image links
            var img = document.createElement("img");            // Loads all the image in a hidden div.
            $(img).attr("src", this.aNodes[i].href);
            preload.appendChild(img);
        }
    }
    

    【讨论】:

    • 你怎么知道它什么时候完成加载呢?我没有对此做太多研究,但我不知道你可以参与其中。
    • 我不确定,但也许对于上述情况,您可以向 img.onload 添加一些内容,它会通知某处图像 x 已加载。加载所有所需的图像后,您就可以发出 all ready 信号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多