I would like to be able to prevent an image that has an ng-src attribute from loading until it is visible in the viewport.
Is this possible with Angular?
Previously I have used the jQuery LazyLoad Plugin , however I am trying to do this without having to have both Angular and jQuery.
IMG tags can leverage native browser lazy loading, which doesn't require any JavaScript. You can still lazy load background images if they're in HTML as an inline style. Plugins like FlyingPress automatically detect and lazy load them.
The loading attribute specifies whether a browser should load an image immediately or to defer loading of off-screen images until for example the user scrolls near them. Tip: Add loading="lazy" only to images which are positioned below the fold.
lazysizes will intelligently load images as the user scrolls through the page and prioritize the images that the user is going to encounter soon.
In case you're still interested, i found out this repo on github : https://github.com/afklm/ng-lazy-image
I tried it and it rocks !
Images are loaded only when appearing in viewport AND you can choose which image to load based on screen size. It means that you can load smaller images for mobile users ;)
In angularjs, lazy loading can be implemented using a directive.
Steps:
Step 1. create directive as follows:
App.directive('lazyLoad', lazyLoad)
function lazyLoad() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
const observer = new IntersectionObserver(loadImg);
const img = angular.element(element)[0];
observer.observe(img)
function loadImg(changes) {
changes.forEach(change => {
if (change.intersectionRatio > 0 && change.target.getAttribute('tempData')) {
change.target.src = change.target.getAttribute('tempData');
}
});
}
};
};
};
Step 2: use lazy-load attribute in tag and replace "ng-src" with tempData eg. In html
<img ng-repeate="obj in objects" lazy-load tempData="obj.srcURL">
Note: we are not directly assigning src because we want to prevent image from sending request to server to load image.
Important Note: Dependence upon es-6. You may get parse error while making a build.
*Solution: npm install --save gulp-uglify-es
You need to update your gulp file after installing command. This will install dependency and your code can make a build now.
That's all!!!
Thank you for reading!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With