From 47ec493fa6eea3e85cb6568aa3093652607e27d7 Mon Sep 17 00:00:00 2001 From: Mawoka Date: Wed, 14 Dec 2022 19:22:32 +0100 Subject: [PATCH] :zap: Lazy-loading images on dashboard --- frontend/src/lib/dashboard/main_slider.svelte | 26 ++++++++++++---- .../src/lib/dashboard/useViewportAction.js | 30 +++++++++++++++++++ 2 files changed, 50 insertions(+), 6 deletions(-) create mode 100644 frontend/src/lib/dashboard/useViewportAction.js diff --git a/frontend/src/lib/dashboard/main_slider.svelte b/frontend/src/lib/dashboard/main_slider.svelte index 9c85624..ec4cef7 100644 --- a/frontend/src/lib/dashboard/main_slider.svelte +++ b/frontend/src/lib/dashboard/main_slider.svelte @@ -14,6 +14,7 @@ import { getLocalization } from '$lib/i18n'; import StartGamePopup from './start_game.svelte'; import { onMount } from 'svelte'; + import viewport from './useViewportAction.js'; let copy_toast_open = false; let start_game = null; @@ -29,6 +30,8 @@ }); window.location.reload(); }; + let visibleImages = Array.from(Array(quizzes.length), () => []); + const close_start_game_if_esc_is_pressed = (key: KeyboardEvent) => { if (key.code === 'Escape') { start_game = null; @@ -46,6 +49,7 @@ document.body.addEventListener('keydown', close_start_game_if_esc_is_pressed); }); $: console.log(quizzes, 'quizzes_here'); + $: console.log(visibleImages, 'visible images'); {#if copy_toast_open} @@ -140,6 +144,7 @@ class="max-h-full max-w-full block" src={quiz.cover_image} alt="Not provided" + loading="lazy" /> @@ -265,7 +270,7 @@

- {#each quiz.questions as question} + {#each quiz.questions as question, q}
@@ -273,14 +278,23 @@
{#if question.image}
{ + visibleImages[i][q] = true; + }} + on:exitViewport={() => { + visibleImages[i][q] = false; + }} class="flex justify-center align-middle items-center" >
- Not provided + {#if visibleImages?.[i]?.[q]} + Not provided + {/if}
{/if} diff --git a/frontend/src/lib/dashboard/useViewportAction.js b/frontend/src/lib/dashboard/useViewportAction.js new file mode 100644 index 0000000..fee000b --- /dev/null +++ b/frontend/src/lib/dashboard/useViewportAction.js @@ -0,0 +1,30 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ +// Stolen from https://svelte.dev/repl/c6a402704224403f96a3db56c2f48dfc?version=3.55.0 +let intersectionObserver; + +function ensureIntersectionObserver() { + if (intersectionObserver) return; + + intersectionObserver = new IntersectionObserver((entries) => { + entries.forEach((entry) => { + const eventName = entry.isIntersecting ? 'enterViewport' : 'exitViewport'; + entry.target.dispatchEvent(new CustomEvent(eventName)); + }); + }); +} + +export default function viewport(element) { + ensureIntersectionObserver(); + + intersectionObserver.observe(element); + + return { + destroy() { + intersectionObserver.unobserve(element); + } + }; +}