Lab 08: HTML5 APIs

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Overview

Explore the browser Observer APIs (Intersection, Resize, Mutation), Web Storage (localStorage/sessionStorage), and Custom Elements. These APIs enable performant, declarative web applications without polling.


Step 1: Intersection Observer

Detect when elements enter/exit the viewport without scroll event listeners:

// Basic usage
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('visible');
      observer.unobserve(entry.target); // stop watching once visible
    }
  });
});

document.querySelectorAll('.animate-on-scroll').forEach(el => {
  observer.observe(el);
});

// With options
const lazyObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;  // load image
      img.removeAttribute('data-src');
      lazyObserver.unobserve(img);
    }
  });
}, {
  root: null,          // null = viewport
  rootMargin: '0px 0px -100px 0px',  // trigger 100px before bottom edge
  threshold: 0.1       // 10% visible triggers callback
});

// Multiple thresholds
const progressObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    // entry.intersectionRatio: 0.0 to 1.0
    entry.target.style.opacity = entry.intersectionRatio;
  });
}, {
  threshold: [0, 0.1, 0.25, 0.5, 0.75, 1.0]
});

💡 The rootMargin uses CSS shorthand (top right bottom left). Negative values shrink the intersection area, positive values expand it.


Step 2: Resize Observer

React to element size changes:


Step 3: Mutation Observer

Watch for DOM changes:


Step 4: Web Storage


Step 5: Custom Elements


Step 6: Template & Slot (for Custom Elements)


Step 7: Practical Patterns


Step 8: Capstone — jsdom API Simulation

📸 Verified Output:


Summary

API
Constructor
Key Methods

IntersectionObserver

new IntersectionObserver(cb, opts)

observe(), unobserve(), disconnect()

ResizeObserver

new ResizeObserver(cb)

observe(), unobserve(), disconnect()

MutationObserver

new MutationObserver(cb)

observe(el, config), disconnect()

localStorage

Built-in

setItem(), getItem(), removeItem(), clear()

sessionStorage

Built-in

Same as localStorage

Custom Elements

customElements.define()

connectedCallback, disconnectedCallback, attributeChangedCallback

Last updated