可视区域(可见区域)图片加载,图片延迟加载 javascript lazyload

Posted by jerry.jobs in javascript | Leave a comment

在页面加载区域较大时,并不是所有的图片用户都会浏览到。
如果同步加载用户却不曾浏览到,这就造成资源浪费。
何不搜索可视区域图片并异步加载。

下图为浏览器网页坐标系。
1、A方框为可视区域;
2、红色小方框分别为 1 2 3 号图片(图片使用Php加载,请放入Php环境执行);
3、leftTop(ltx,lty) 代表可视区域左上角坐标;
4、rightBottom(rbx,rby) 代表可视区域右下角坐标;
5、targetPoint (offset.left,offset.top) 代表图片左上角坐标;

示例代码展示流程:
注意:count.log文件将记录当前已读取的图片,在展示前请用可提示更新的编辑器打开(如:EditPlus)。
1、打开页面即可看到 1号图片 (count.log 记录为 1);
2、将滚轮向下拖动则可看到 2号图片;(count.log 记录为 1 2);
2、将滚轮向上并向右拖动则可看到 3号图片;(count.log 记录为 1 2 3,1号图片不会重复加载);
主要脚本:

 


// 注意本方法建立在jquery基础之上,必先加载jquery

function lazyLoad(){
    jQuery("img[src^='#']").each(function(){
        var img = jQuery(this);
        var win = jQuery(window);
        /*
        leftTop(ltx,lty)
        rightBottom(rbx,rby)
        targetPoint (offset.left,offset.top)
        */
        var offset = img.offset();
        var ltx = win.scrollLeft(); // left top x
        var lty = win.scrollTop(); // left top y

        var rbx = win.scrollLeft()  + win.width(); // right bottom x
        var rby = win.scrollTop() + win.height(); // right bottom y
        if (offset.left >= ltx && offset.left <= rbx
                      && offset.top >= lty && offset.top <= rby ) {
            img.attr("src",img.attr("src").substr(1));
        }
    });
}

jQuery(window).scroll( function() {
    lazyLoad();
});

jQuery(function() {
    lazyLoad();
});

下载演示例子: imageLazyLoad

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>