A: 怎样完成 Lazy Load?

近来面试了几家公司,他们不谋而合都问到了这个题目:相识 Lazy Load 吗?

Lazy Load is delays loading of images in long web pages. Images outside of viewport are not loaded until user scrolls to them. This is opposite of image preloading.

Using Lazy Load on long web pages will make the page load faster. In some cases it can also help to reduce server load.

Lazy Load实际上是对图片的一种耽误加载手艺,直到用户转动图片出如今用户可视局限时才把它加载出来。它与图片预加载手艺完整相反,却都是为了进步用户体验而设想。

Lazy Load Plugin for jQuery – Mika Tuupola

jQuery的Lazy Load插件人人应当都有相识或许已运用过了。下面是一个简朴的栗子:


    <img class="lazy" data-original="img/example.jpg" width="640" height="480">
    
    $(function() {
        $("img.lazy").lazyload();//能够传入自定义的参数
    });

data-original属性值是我们想要显现的图片的URL,当用户转动页面,图片出如今视线局限内时,替代img元素的src属性值为data-original属性值。

不过仅仅相识这些彷佛远远不够。我在网上查找了一些Lazy Load的完成道理,发明了以下的代码:

    // 原生JS完成要领
    <script>
        var imgs = document.getElementsByTagName('img');
        // 猎取视口高度与转动条的偏移量
        function lazyload(){
            // 猎取当前转动条偏移量
            var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
            // 猎取视口高度
            var viewportSize = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            for(var i=0; i<imgs.length; i++) {
                var x =scrollTop+viewportSize-imgs[i].offsetTop;
                if(x>0){
                    imgs[i].src = imgs[i].getAttribute('loadpic');   
                }
            }
        }
        setInterval(lazyload,1000);
    </script>

这位老铁本身写了一段大略的完成代码,他用了定时器轮回挪用lazyload要领,固然人人能够先疏忽,重点看一下怎样猎取当前转动条的位置和视口的高度。

    var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

这个东西我刚看也是一头雾水。我在chrome上亲自实践了一下,但是发明,document.documentElement.scrollTop老是返回0,其他两种要领都一般猎取到了值。因而查了一下才晓得这三个猎取转动条位置的要领背地另有故事。看这个题目:

document.documentElement.scrollTop return value differs in Chrome

另有个中一名老铁的回复:

The standards-based way of getting the scroll is window.scrollY. This is supported by Chrome, Firefox, Opera, Safari and IE Edge or later. If you only support these browsers, you should go with this property.

IE >= 9 supports a similar property window.pageYOffset, which for the sake of compatibility returns the same as window.scrollY in recent browsers, though it may perhaps be deprecated at some point.

The problem with using document.documentElement.scrollTop or document.body.scrollTop is that the scroll needn’t be defined on either of these. Chrome and Safari define their scroll on the <body> element whilst Firefox defines it on the <html> element returned by document.documentElement, for example. This is not standardized, and could potentially change in future versions of the browsers. However, if the scrollY or pageYOffset are not present, this is the only way to get the scroll.

window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0)

那这故事我就不讲了。

    var viewportSize = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

这行代码是为了猎取视口的高度,我们一样看到了三种要领,那他们背地一定也有不为我知的故事,如今我也不太想晓得了。

    var x =scrollTop+viewportSize-imgs[i].offsetTop;

怎样取得一个元素与页面顶端的间隔,你学会了吗?

下面是用jQuery完成的lazyload,也是适才那位老铁写的:

    /**
    * 图片的src完成道理
    */
    $(document).ready(function(){
        // 猎取页面视口高度
        var viewportHeight = $(window).height();
        var lazyload = function() {
            // 猎取窗口转动条间隔
            var scrollTop = $(window).scrollTop();
            $('img').each(function(){
            // 推断 视口高度+转动条间隔 与 图片元素间隔文档原点的高度         
            var x = scrollTop + viewportHeight - $(this).position().top;
            // 假如大于0 即该元素能被阅读者看到,则将暂存于自定义属性loadpic的值赋值给真正的src            
            if (x > 0)
            {
                $(this).attr('src',$(this).attr('loadpic')); 
            }
        })
        }
        // 建立定时器 “及时”盘算每一个元素的src是不是应当被赋值
        setInterval(lazyload,100);
    });

上述的完成呢,我觉得照样能够压服我的,把定时器去掉,到场对转动事宜的侦听即可。不过,就这么敷衍了事彷佛也没什么意义,我下载了jQuery-lazyload的源码,预备研讨一波。假如我看懂了什么,或许有什么收成,再来聊聊。

    /*!
     * Lazy Load - jQuery plugin for lazy loading images
     *
     * Copyright (c) 2007-2015 Mika Tuupola
     *
     * Licensed under the MIT license:
     *   http://www.opensource.org/licenses/mit-license.php
     *
     * Project home:
     *   http://www.appelsiini.net/projects/lazyload
     *
     * Version:  1.9.7
     *
     */
    (function($, window, document, undefined) {
      // body...
    })(jQuery, window, document);
    原文作者:t1ree
    原文地址: https://segmentfault.com/a/1190000008840116
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞