Skip to content

Instantly share code, notes, and snippets.

@galanggg
Created October 19, 2024 01:54
Show Gist options
  • Save galanggg/b05acf78cc6487b16f8af872534b1c44 to your computer and use it in GitHub Desktop.
Save galanggg/b05acf78cc6487b16f8af872534b1c44 to your computer and use it in GitHub Desktop.
Intersection Observer API with Document Fragment
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Frontend System Design Fundamentals</title>
<link rel="stylesheet" href="../../styles/index.css">
<template id="card_template">
<article class="card">
<h3 class="card__title"></h3>
<div class="card__body">
<div class='card__body__image'></div>
<section class='card__body__content'>
</section>
</div>
</article>
</template>
</head>
<body>
<main id="container">
<div id="list"></div>
<div id="bottom-observer">
Bottom Observer
</div>
</main>
<script type="module">
import {initMockDB} from "../../utils/db.js";
const [template, list, observerElement] = document.querySelectorAll("#card_template, #list, #bottom-observer");
const db = initMockDB({
title: "Fundamentals of Frontend System Design",
body: "Learning to use Intersection Observer"
});
function createCardElement(title, body) {
const element = template.content.cloneNode(true).firstElementChild;
const [cardTitle, cardBody] = element.querySelectorAll('.card__title, .card__body__content');
[cardTitle.textContent, cardBody.textContent] = [title, body];
return element;
}
/**
* Exercise - Intersection Observer
* 1. Create Intersection observer instance and provide a callback to it
* 2. In the callback use mock db - next function to get the next chunk of data
* 3. Create a fragment where you chunk all your DOM Mutations
* 4. Update fragment
* 5. Append fragment to "list" container
*/
let page = 0;
const observer = new IntersectionObserver(async (entries) => {
if (!entries[0].isIntersecting) return;
const data = await db.getPage(page++)
const fragment = document.createDocumentFragment();
data.forEach(({title, body}) => {
fragment.appendChild(createCardElement(title, body));
});
list.appendChild(fragment);
}, {
threshold: 0.2
});
observer.observe(observerElement)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment