From a8a8f374444a171e41e7f8852f9ae620c488104f Mon Sep 17 00:00:00 2001 From: Cotes Chung <11371340+cotes2020@users.noreply.github.com> Date: Mon, 19 Aug 2024 21:05:39 +0800 Subject: [PATCH] refactor: improve the efficiency of `GLightbox` switching Repeatedly using `GLightbox.destroy()` (>= 4 times) will cause `GLightbox` to fail to generate new objects --- _javascript/modules/components/img-popup.js | 22 +++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/_javascript/modules/components/img-popup.js b/_javascript/modules/components/img-popup.js index 6c3e733ad8f..d0f7ba509f3 100644 --- a/_javascript/modules/components/img-popup.js +++ b/_javascript/modules/components/img-popup.js @@ -9,15 +9,18 @@ const lightImages = '.popup:not(.dark)'; const darkImages = '.popup:not(.light)'; let selector = lightImages; -function updateImages(lightbox) { +function updateImages(current, reverse) { if (selector === lightImages) { selector = darkImages; } else { selector = lightImages; } - lightbox.destroy(); - lightbox = GLightbox({ selector: `${selector}` }); + if (reverse === null) { + reverse = GLightbox({ selector: `${selector}` }); + } + + [current, reverse] = [reverse, current]; } export function imgPopup() { @@ -25,6 +28,11 @@ export function imgPopup() { return; } + const hasDualImages = !( + document.querySelector('.popup.light') === null && + document.querySelector('.popup.dark') === null + ); + if ( (html.hasAttribute('data-mode') && html.getAttribute('data-mode') === 'dark') || @@ -34,16 +42,18 @@ export function imgPopup() { selector = darkImages; } - let lightbox = GLightbox({ selector: `${selector}` }); + let current = GLightbox({ selector: `${selector}` }); + let reverse = null; if (document.getElementById('mode-toggle')) { window.addEventListener('message', (event) => { if ( event.source === window && event.data && - event.data.direction === ModeToggle.ID + event.data.direction === ModeToggle.ID && + hasDualImages ) { - updateImages(lightbox); + updateImages(current, reverse); } }); }