From 2cd70552b02765bd5142c328d8c5cf5be6481939 Mon Sep 17 00:00:00 2001 From: TLRZ Seyfferth Date: Wed, 6 May 2020 19:37:58 +0200 Subject: [PATCH] [TASK] starting lazy-load --- Packages/chrosey_materialize/js/site.js | 38 ++++++++++++++++++- .../chrosey_materialize/partials/images.twig | 9 +++-- .../chrosey_materialize/templates/blog.twig | 6 ++- .../templates/layout/navigationBar.twig | 5 ++- 4 files changed, 50 insertions(+), 8 deletions(-) diff --git a/Packages/chrosey_materialize/js/site.js b/Packages/chrosey_materialize/js/site.js index 216747b..94b175e 100644 --- a/Packages/chrosey_materialize/js/site.js +++ b/Packages/chrosey_materialize/js/site.js @@ -1 +1,37 @@ -M.AutoInit(); \ No newline at end of file +M.AutoInit(); + +// Set up an intersection observer with some options +var observer = new IntersectionObserver(lazyLoad, { + + // where in relation to the edge of the viewport, we are observing + rootMargin: "100px", + + // how much of the element needs to have intersected + // in order to fire our loading function + threshold: 1.0 + +}); + +function lazyLoad(elements) { + elements.forEach(image => { + if (image.intersectionRatio > 0) { + + // set the src attribute to trigger a load + image.src = image.dataset.src; + + // stop observing this element. Our work here is done! + observer.unobserve(item.target); + }; + }); +}; + +// If the browser supports lazy loading, we can safely assign the src +// attributes without instantly triggering an eager image load. +if ("loading" in HTMLImageElement.prototype) { + const lazyImages = document.querySelectorAll("img.lazy"); + lazyImages.forEach(img => { + img.src = img.dataset.src; + }); +} else { + // Use our own lazyLoading with Intersection Observers and all that jazz +} \ No newline at end of file diff --git a/Packages/chrosey_materialize/partials/images.twig b/Packages/chrosey_materialize/partials/images.twig index 58e245b..961c201 100644 --- a/Packages/chrosey_materialize/partials/images.twig +++ b/Packages/chrosey_materialize/partials/images.twig @@ -5,15 +5,18 @@ {% for image in images %} - {{ image.alt }} {% endfor %} {% else %} - {{ images.0.alt }} {% endif %} diff --git a/Packages/chrosey_materialize/templates/blog.twig b/Packages/chrosey_materialize/templates/blog.twig index 6313451..44ef36c 100644 --- a/Packages/chrosey_materialize/templates/blog.twig +++ b/Packages/chrosey_materialize/templates/blog.twig @@ -9,8 +9,10 @@
- {{ images.0.alt }} + {{ images.0.alt }} chevron_right diff --git a/Packages/chrosey_materialize/templates/layout/navigationBar.twig b/Packages/chrosey_materialize/templates/layout/navigationBar.twig index 874bd79..3e4b617 100644 --- a/Packages/chrosey_materialize/templates/layout/navigationBar.twig +++ b/Packages/chrosey_materialize/templates/layout/navigationBar.twig @@ -4,8 +4,9 @@