图片预加载技术

一般像一些网站在显示图片时,需要预加载技术,避免图片加载时显示死图的现象。有了预加载技术,可以结合进度条显示,把图片集提前加载出来,这样在图片播放过程中就比较流畅,体验就比较好。

1、首先可以尝试写一个没有预加载技术的图片切换效果,我整理的是js代码,前端显示的代码就不提供了。

$(".btn").on("click",function(){
        var control=$(this).data("control");
        if(control==="prev"){
            index=Math.max(0,--index);
        }else{
            index=Math.min(len-1,++index);
        }
        $(".title").html((index+1)+"/"+len);
        $(".img").attr("src",img[index]);    
    })

2、接下来,使用预加载技术,在点击轮播效果之前,先把图片加载出来。可以结合进度条来传达加载的效果。

    var index=0,
        len=img.length,
        count=0,
        $progress=$(".jindu");
    $.each(img,function(i,src){
        var imgobj=new Image();
        $(imgobj).on("load",function(){
            $progress.html(Math.round((count+1)/len*100)+"%");
            if(count>=len-1){
                $(".loading").hide();
                $(".title").html("1/"+len);
            }
            count++;
        })
        imgobj.src=src;
    })

3、注意,图片集合是通过路径保存的一个数组。

var img=[
        'http://test.huiliewang.com/images/banner1.jpg',
        'http://test.huiliewang.com/images/banner2.jpg',
        'http://test.huiliewang.com/images/banner3.jpg',
        'http://www.nfxhlt.com/picture/b1.jpg',
        'http://www.nfxhlt.com/picture/b2.jpg',
        'http://www.nfxhlt.com/picture/b3.jpg'
        ];

通过以上的预加载技术,实现图片提前加载,确保点击下一页、上一页、自动轮播的流畅显示效果。

原文地址:https://www.cnblogs.com/zjingjing/p/8350338.html