From 29383f37e749e33d90e87448a89a4f21583a8cc8 Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Tue, 1 Oct 2019 18:21:46 +0200 Subject: [PATCH] V8: Lazy load thumbnails in the media grid (#6510) --- .../components/umbimagelazyload.directive.js | 72 +++++++++++++++++++ .../src/views/components/umb-media-grid.html | 2 +- 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 src/Umbraco.Web.UI.Client/src/common/directives/components/umbimagelazyload.directive.js diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbimagelazyload.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbimagelazyload.directive.js new file mode 100644 index 0000000000..9d76993fd3 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbimagelazyload.directive.js @@ -0,0 +1,72 @@ +/** +@ngdoc directive +@name umbraco.directives.directive:umbImageLazyLoad +@restrict E +@scope + +@description +Use this directive to lazy-load an image only when it is scrolled into view. + +

Markup example

+
+    
+ +
+
+ +

Controller example

+
+    (function () {
+        "use strict";
+
+        function Controller() {
+
+            var vm = this;
+            vm.imageUrl = "/media/TODO";
+        }
+
+        angular.module("umbraco").controller("My.Controller", Controller);
+    })();
+
+ +**/ + +(function() { + 'use strict'; + + function ImageLazyLoadDirective() { + + const placeholder = "assets/img/transparent.png"; + + function link(scope, element, attrs) { + + const observer = new IntersectionObserver(loadImg); + const img = angular.element(element)[0]; + img.src = placeholder; + observer.observe(img); + + function loadImg(changes) { + changes.forEach(change => { + if (change.intersectionRatio > 0 && change.target.src.indexOf(placeholder) > 0) { + change.target.src = attrs.umbImageLazyLoad; + } + }); + } + + // make sure to disconnect the observer when the scope is destroyed + scope.$on('$destroy', function () { + observer.disconnect(); + }); + } + + var directive = { + restrict: "A", + link: link + }; + + return directive; + } + + angular.module('umbraco.directives').directive('umbImageLazyLoad', ImageLazyLoadDirective); + +})(); diff --git a/src/Umbraco.Web.UI.Client/src/views/components/umb-media-grid.html b/src/Umbraco.Web.UI.Client/src/views/components/umb-media-grid.html index 0ab15437b9..5923845539 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/umb-media-grid.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/umb-media-grid.html @@ -13,7 +13,7 @@
- {{item.name}} + {{item.name}} {{item.name}}