From: Ardis Lu Date: Mon, 9 Sep 2024 06:34:50 +0000 (-0700) Subject: Re-use ResizeObserver instead of instantiating new ones X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=fb62d514e2fd8becdc321a7c79ab064dbdd762ea;p=ardislu.dev Re-use ResizeObserver instead of instantiating new ones --- 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; }