欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ionic图片懒加载的实现整合 --ionic-image-lazy-load.js

程序员文章站 2022-04-13 15:41:47
...

实现ionic的图片懒加载,用ionic-image-lazy-load,一般而言有两种类型的js,基本上是一样的。
第一种:这里我命名为lazy-load.js
1.引入js,在index页面加上

<script src="js/lazy-load.js"></script>

2.修改对应的html:图片部分修改为下列代码
在ion-content加上scroller,作为监听滚动事件所用

<img src="./img/noimg.png" onerror="this.src='./img/noimg.png'" image-lazy-src="{{ item.image }}">

其中

src="./img/noimg.png" onerror="this.src='./img/noimg.png'"

部分是用于请求图片等待时所用的本地图片地址。
3.修改js:(页面的控制器名称为DashCtrl)

angular.module('starter.controllers', ['ionic','ionic-img-lazy-load'])

.controller('DashCtrl', function($scope) {
  $scope.items = [
    { id: 1, album: 'Gotta Be Somebody', artist: 'Nickelback', image: 'http://img03.sogoucdn.com/app/a/100520093/60d2f4fe0275d790-fbe7539243950f9f-7f669dbeead0ad667f21be96b5efd843.jpg' },
    { id: 2, album: 'Dark Horse', artist: 'Nickelback', image: 'http://img03.sogoucdn.com/app/a/100520093/60d2f4fe0275d790-fbe7539243950f9f-7f669dbeead0ad667f21be96b5efd843.jpg' },
    { id: 3, album: 'Someday', artist: 'Nickelback', image: 'http://img03.sogoucdn.com/app/a/100520093/60d2f4fe0275d790-fbe7539243950f9f-7f669dbeead0ad667f21be96b5efd843.jpg' },
    { id: 4, album: 'All The Right Reasons', artist: 'Nickelback', image: 'http://img03.sogoucdn.com/app/a/100520093/60d2f4fe0275d790-fbe7539243950f9f-7f669dbeead0ad667f21be96b5efd843.jpg' }

  ];
})

注意对应的lazy-load.js中的名字要对应的名
ionic图片懒加载的实现整合 --ionic-image-lazy-load.js

第二种:与第一种相似(不仔细说明了),步骤如下:
1.

<script src="js/ionic-image-lazy-load.js"></script>

2.修改对应的html:图片部分修改为下列代码
在ion-content加上lazy-scroll,作为监听滚动事件所用

<img image-lazy-loader="spiral" src="./img/noimg.png" onerror="this.src='./img/noimg.png'" image-lazy-src="{{ item.image }}">

其中

src="./img/noimg.png" onerror="this.src='./img/noimg.png'"

部分是用于请求图片等待时所用的本地图片地址。

image-lazy-loader="spiral"

这个是加载时的动画

3.js:主要是加上这个,把名字改了

angular.module('starter.controllers', ['ionic','ionicLazyLoad'])

另:
lazy-load.js代码为:

angular.module('ionic-img-lazy-load', []);

angular.module('ionic-img-lazy-load').directive(
    'scroller', function ($rootScope, $timeout) {
        return {
            restrict: 'A',
            link: function ($scope, $element) {

                var scrollTimeoutId = 0;

                $scope.invoke = function () {
                    $rootScope.$broadcast('scrollEvent');
                };

                $element.bind('scroll', function () {

                    $timeout.cancel(scrollTimeoutId);

                    // wait for 200ms and then invoke listeners (simulates stop event)
                    scrollTimeoutId = $timeout($scope.invoke, 50);

                });


            }
        };
    });

angular.module('ionic-img-lazy-load').directive(
    'imageLazySrc', function ($document) {
        return {
            restrict: 'A',
            link: function ($scope, $element, $attributes) {

                var deregistration = $scope.$on('scrollEvent', function () {
                        console.log('scroll');
                        if (isInView()) {
                            $element[0].src = $attributes.imageLazySrc; // set src attribute on element (it will load image)
                            deregistration();
                        }
                    }
                );

                function isInView() {

                    var clientHeight = $document[0].documentElement.clientHeight;
                    var clientWidth = $document[0].documentElement.clientWidth;
                    var imageRect = $element[0].getBoundingClientRect();
                    return  (imageRect.top >= 0 && imageRect.bottom <= clientHeight) && (imageRect.left >= 0 && imageRect.right <= clientWidth);
                }

                // bind listener
                // listenerRemover = scrollAndResizeListener.bindListener(isInView);

                // unbind event listeners if element was destroyed
                // it happens when you change view, etc
                $element.on('$destroy', function () {
                    deregistration();
                });

                // explicitly call scroll listener (because, some images are in viewport already and we haven't scrolled yet)
                if (isInView()) {
                    $element[0].src = $attributes.imageLazySrc; // set src attribute on element (it will load image)
                    deregistration();
                }
            }
        };
    }
);

ionic-image-lazy-load.js代码为:

angular.module('ionicLazyLoad', []);

angular.module('ionicLazyLoad')

.directive('lazyScroll', ['$rootScope',
    function($rootScope) {
        return {
            restrict: 'A',
            link: function ($scope, $element) {
                var origEvent = $scope.$onScroll;
                $scope.$onScroll = function () {
                    $rootScope.$broadcast('lazyScrollEvent');

                    if(typeof origEvent === 'function'){
                      origEvent();
                    }
                };
            }
        };
}])

.directive('imageLazySrc', ['$document', '$timeout', '$ionicScrollDelegate', '$compile',
    function ($document, $timeout, $ionicScrollDelegate, $compile) {
        return {
            restrict: 'A',
            scope: {
                lazyScrollResize: "@lazyScrollResize",
                imageLazyBackgroundImage: "@imageLazyBackgroundImage",
                imageLazySrc: "@"
            },
            link: function ($scope, $element, $attributes) {
                if (!$attributes.imageLazyDistanceFromBottomToLoad) {
                    $attributes.imageLazyDistanceFromBottomToLoad = 0;
                }
                if (!$attributes.imageLazyDistanceFromRightToLoad) {
                    $attributes.imageLazyDistanceFromRightToLoad = 0;
                }

                var loader;
                if ($attributes.imageLazyLoader) {
                    loader = $compile('<div class="image-loader-container"><ion-spinner class="image-loader" icon="' + $attributes.imageLazyLoader + '"></ion-spinner></div>')($scope);
                    $element.after(loader);
                }

                $scope.$watch('imageLazySrc', function (oldV, newV) {
                    if(loader)
                        loader.remove();
                    if ($attributes.imageLazyLoader) {
                        loader = $compile('<div class="image-loader-container"><ion-spinner class="image-loader" icon="' + $attributes.imageLazyLoader + '"></ion-spinner></div>')($scope);
                        $element.after(loader);
                    }
                    var deregistration = $scope.$on('lazyScrollEvent', function () {
                        //    console.log('scroll');
                            if (isInView()) {
                                loadImage();
                                deregistration();
                            }
                        }
                    );
                    $timeout(function () {
                        if (isInView()) {
                            loadImage();
                            deregistration();
                        }
                    }, 500);
                });
                var deregistration = $scope.$on('lazyScrollEvent', function () {
                       // console.log('scroll');
                        if (isInView()) {
                            loadImage();
                            deregistration();
                        }
                    }
                );

                function loadImage() {
                    //Bind "load" event
                    $element.bind("load", function (e) {
                        if ($attributes.imageLazyLoader) {
                            loader.remove();
                        }
                        if ($scope.lazyScrollResize == "true") {
                            //Call the resize to recalculate the size of the screen
                            $ionicScrollDelegate.resize();
                        }
                        $element.unbind("load");
                    });

                    if ($scope.imageLazyBackgroundImage == "true") {
                        var bgImg = new Image();
                        bgImg.onload = function () {
                            if ($attributes.imageLazyLoader) {
                                loader.remove();
                            }
                            $element[0].style.backgroundImage = 'url(' + $attributes.imageLazySrc + ')'; // set style attribute on element (it will load image)
                            if ($scope.lazyScrollResize == "true") {
                                //Call the resize to recalculate the size of the screen
                                $ionicScrollDelegate.resize();
                            }
                        };
                        bgImg.src = $attributes.imageLazySrc;
                    } else {
                        $element[0].src = $attributes.imageLazySrc; // set src attribute on element (it will load image)
                    }
                }

                function isInView() {
                    var clientHeight = $document[0].documentElement.clientHeight;
                    var clientWidth = $document[0].documentElement.clientWidth;
                    var imageRect = $element[0].getBoundingClientRect();
                    return (imageRect.top >= 0 && imageRect.top <= clientHeight + parseInt($attributes.imageLazyDistanceFromBottomToLoad))
                        && (imageRect.left >= 0 && imageRect.left <= clientWidth + parseInt($attributes.imageLazyDistanceFromRightToLoad));
                }

                // bind listener
                // listenerRemover = scrollAndResizeListener.bindListener(isInView);

                // unbind event listeners if element was destroyed
                // it happens when you change view, etc
                $element.on('$destroy', function () {
                    deregistration();
                });

                // explicitly call scroll listener (because, some images are in viewport already and we haven't scrolled yet)
                $timeout(function () {
                    if (isInView()) {
                        loadImage();
                        deregistration();
                    }
                }, 500);
            }
        };
    }]);
相关标签: ionic lazy-load