【问题标题】:jquery plugin preloading imagesjquery插件预加载图像
【发布时间】:2013-11-21 18:31:13
【问题描述】:

我制作了一个 jquery 插件来显示图像: http://jsfiddle.net/wfARj/

他的一个功能是预加载图像:

function preload(){
        for (var i = firstIndex; i <= lastIndex; i++) {
            images[i] = new Image();
            images[i].onload = function(response){
                console.log(this.src + ' is successfully loaded!');
            }
            images[i].src = $(selector).eq(i).attr('href');
        }

} 

问题如下,当一些照片很大(>5MB)时,网站加载太慢了。

我尝试:

function preload(){
    setTimeout(function(){
            for(var i = firstIndex;i <= lastIndex;i++)
            {
                images[i] = new Image();
                images[i].onload = function(response){
                    console.log(this.src + ' is successfully loaded!');
                }
                if(elementType=='A') images[i].src = $(selector).eq(i).attr('href');
                else if(elementType=='IMG') images[i].src =            $(selector).eq(i).attr('src');
                else images[i].src = '';
            }
        }, 300);
}

但问题仍然存在... 我想在页面加载后在后台预加载图像。 使用 window.bind 加载检测整页加载不是安全选项。 我该如何解决这个问题?

谢谢

【问题讨论】:

    标签: javascript jquery html jquery-plugins preloading


    【解决方案1】:

    但是 for 循环闭包中的 settimeout,因此每个加载调用都有自己的超时。

    function preload(){
                for(var i = firstIndex;i <= lastIndex;i++)
                {
                    setTimeout(function(){
                        images[i] = new Image();
                        images[i].onload = function(response){
                             console.log(this.src + ' is successfully loaded!');
                        }
                        if(elementType=='A') images[i].src = $(selector).eq(i).attr('href');
                        else if(elementType=='IMG') images[i].src =   $(selector).eq(i).attr('src');
                        else images[i].src = '';
                    }, 300);
            }
    }
    

    【讨论】:

    • 确保所有变量仍在范围内。
    • 我使用 $.each 循环,然后一切正常,没有错误,但页面仍然加载缓慢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多