From fb62d514e2fd8becdc321a7c79ab064dbdd762ea Mon Sep 17 00:00:00 2001 From: Ardis Lu Date: Sun, 8 Sep 2024 23:34:50 -0700 Subject: [PATCH] Re-use ResizeObserver instead of instantiating new ones --- script.js | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/script.js b/script.js index 5770d61..eaf0787 100644 --- a/script.js +++ b/script.js @@ -61,6 +61,16 @@ async function fetchPostMetadata() { return metadata; } +// Sets grid-row-end for each card when the homepage is resized. Required to implement masonry layout. +const observer = new ResizeObserver(home => { + for (const card of home.children) { + const contentHeight = Array.from(card.children).reduce((acc, cur) => acc + cur.clientHeight, 0); + const cardHeight = contentHeight + 128; // 6 * 16px gaps + 2 * 16px padding + card.style.gridRowEnd = `span ${Math.ceil(cardHeight / 16)}`; // 16px grid gap + card.style.maxBlockSize = `${cardHeight}px`; + } +}); + /* Constructs the
element used on the homepage from the CMS metadata Map object. */ function buildHomeComponent(metadata) { const home = document.createElement('main'); @@ -86,15 +96,8 @@ function buildHomeComponent(metadata) { `); } - // Sets grid-row-end for each card when the homepage is resized. Required to implement masonry layout. - new ResizeObserver(_ => { - for (const card of home.children) { - const contentHeight = Array.from(card.children).reduce((acc, cur) => acc + cur.clientHeight, 0); - const cardHeight = contentHeight + 128; // 6 * 16px gaps + 2 * 16px padding - card.style.gridRowEnd = `span ${Math.ceil(cardHeight / 16)}`; // 16px grid gap - card.style.maxBlockSize = `${cardHeight}px`; - } - }).observe(home); + observer.disconnect(); + observer.observe(home); return home; } -- 2.47.3