图片预加载和懒加载

原创 15801206036 随笔 css 351阅读 2017-12-14 15:37:31 举报

1.关于图片的懒加载和预加载个人理解差异,懒加载是首先加载一部分(一般是首屏图),然后到需要展示的时候再加载需要的内容,而预加载也是先加载一部分(一般是首屏图),然后页面元素加载完毕后再预加载其他图片,当需要展示的时候直接从缓存中获取就好,是已经加载好的。
2,懒加载的使用,个人现在一直用的lazy.js,作者是谁忘了,哈哈上代码
//图片懒加载
function lazyLoadImg() {
(function($) {

    var defaults = {
        coverColor: "#dfdfdf",
        coverDiv: "",
        showTime: 300,
        offsetBottom: 0,
        offsetTopm: 50,
        onLoadBackEnd: function(index, dom) {},
        onLoadBackStart: function(index, dom) {}
    }

    //所有待load src
    var srcList = []

    var lazyLoadCoutn = 0;
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    var lazyImgList = $("img[data-lazy-src]");
    var default_base64_src = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";

    //获取img
    function getImgNaturalDimensions(src, callback, lazyLoadCoutn) {
        var nWidth, nHeight

        var image = new Image()
        image.src = src;
        image.onload = function() {
            callback(image.width, image.height);
            defaults.onLoadBackStart(lazyLoadCoutn, $("img[data-lazy-src]:eq(" + lazyLoadCoutn + ")"));
        }
        return [nWidth, nHeight];
    }

    function showImg(lazyLoadCoutn, callback) {

        var src = lazyImgList.eq(lazyLoadCoutn).attr("data-lazy-src")
        getImgNaturalDimensions(src, function() {
            try {

                meng($("img[data-lazy-src]:eq(" + lazyLoadCoutn + ")"), lazyLoadCoutn, callback)
            } catch(error) {

            }
        }, lazyLoadCoutn)
    }

    function meng(jDom, lazyLoadCoutn, callback) {
        if(jDom.attr("data-comp")) {
            return;
        }
        jDom.css("visibility", "hidden");
        jDom.attr("src", jDom.attr("data-lazy-src"))
        var w = jDom.width();
        var h = jDom.height();
        var offsetTop = jDom.offset().top;
        var offsetLeft = jDom.offset().left;
        jDom.css("visibility", "visible");
        $("body").append("<div class='meng-lazy-div" + lazyLoadCoutn + "' style='background-color: " + defaults.coverColor + ";position:absolute;width:" + w + "px;height:" + h + "px;top:" + offsetTop + "px;left:" + offsetLeft + "px;z-index:500'>" + defaults.coverDiv + "</div>");
        noneM(lazyLoadCoutn, callback, jDom);
        jDom.attr("data-comp", "true");
    }

    function noneM(lazyLoadCoutn, callback, jDom) {
        if(true) {
            $(".meng-lazy-div" + lazyLoadCoutn).animate({
                opacity: "0"
            }, defaults.showTime, function() {
                $(this).remove();
                defaults.onLoadBackEnd(lazyLoadCoutn, jDom)
                callback();
            });
        }
    }

    function checkOffset() {
        var scrollTop = $(document).scrollTop();
        var onlazyList = [];
        lazyImgList.each(function(index) {
            var dom = $(this);
            if(!dom.attr("data-comp")) {
                if(dom.offset().top - scrollTop + defaults.offsetTopm >= 0 && dom.offset().top - scrollTop < (windowHeight + defaults.offsetBottom)) {
                    onlazyList.push(index);
                }
            }
        })

        if(onlazyList.length != 0) {
            showImg(onlazyList[0], function() {
                checkOffset();
            });
        }
    }

    function range() {
        checkOffset();

    }

    function init(setting) {
        defaults = $.extend(defaults, setting);

        lazyImgList.each(function() {
            var sr = $(this).attr("data-lazy-src");
            srcList.push(sr);

            $(this).attr("src", default_base64_src);
        });
        range();
        $('.contacts-content').bind("scroll", function() {
            //              console.log(1);
            range()
        })
    }

    window.lazyLoadInit = init;

})($)

lazyLoadInit({
    coverColor: "white",
    //      coverDiv:"",
    offsetBottom: 20,
    offsetTopm: 0,
    showTime: 300,
    onLoadBackEnd: function(i, e) {
        //          console.log("onLoadBackEnd:" + i);
    },
    onLoadBackStart: function(i, e) {
        //          console.log("onLoadBackStart:" + i);
    }
});

};
调用的时候直接将img的src换成data-lazy-src就好,简单好用,不再赘述
2.预加载
预加载需要通过css和js同时控制,首先将需要预加载的图片写到一个元素里例如

preloader {

/*需要预加载的图片*/
background: url(image1.jpg) no-repeat,url(image2.jpg) no-repeat,url(image3.jpg) no-repeat,url(image4.jpg) no-repeat;
width: 0px;
height: 0px;

}
但是如果直接写的话会和页面一起加载增加页面整体加载时间,所以需要配合js当页面加载完毕再加载,上代码
function preloader(urlArr,obj) {
var bgText='';
for(var i=0,len=urlArr.length;i<len;i++){
bgText+='url('+urlArr[i]+') no-repeat,';
}
obj.style.background=bgText.substr(0,bgText.length-1);
}
window.onload = function() {
preloader(['image1.jpg','image2.jpg','image3.jpg'],document.getElementById('preloader'));
}

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复