微信公众号定制开发

ionic图片懒加载

来源:微信部落

公司一个微信的项目用的ionic开发,现在项目开发的差不多了,开始进入优化阶段,一个图片的lazyload就搞了半天,不过最终达到了期望的效果

绑定滚动事件on-scroll

<ion-content on-scroll="scroll()"
// 可见区域的高度
var windowHeight = $(window).height();
$scope.scroll = function(){
    lazyLoadImage();
}
// repeat渲染结束后再lazyload
$scope.$on('ngRepeatFinished', function(){
    lazyLoadImage();
})

// lazyload的实现
function lazyLoadImage(){
    var windowHeight = $(window).height();
    imgCache = $('img.lazyload')
    imgCache.each(function(index, el) {

        if($(el).offset().top - windowHeight < -100){
            var url = $(el).attr('data-url');
            $(el).attr('src', url);
            $(el).removeClass('lazyload');
            $(el).addClass('animated fadeIn');
        }
    });
}
end-repeat指令代码

.directive('endRepeat', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                });
            }
        }
    }
}])
模板代码

<img data-url="{{produce.produce_image}}" class="lazyload" ng-repeat="produce in produces" end-repeat>
原理:将图片的src设置在data-url中,当随着页面滚动,图片进入可视区域时,将src设置为data-url的值

声明:

① 凡本网所有原创文章及图片、图表的版权均属微信部落所有,如需转载,需注明“信息来源:微信部落”,并且添加本文地址:http://wxbuluo.com/index/article/18.html

② 凡本网注明“来源:XXX(非微信部落)”的文字及图片内容,均转载自其他媒体,版权归原媒体及作者所有。转载目的在于传递更多的资讯,并不代表本网赞同其观点和对其真实性负责。如有侵权,请联系删除。联系方式:296720094@qq.com

上一篇:ionic的ion-infinite-scroll在加载的时候会请求两次

下一篇:没有更多文章了