typescript 41 lines · 7 steps

Lazy-loading images with IntersectionObserver

Defer image loading until each element scrolls near the viewport, with a graceful fallback and a cleanup handle.

Explained by highlit
1type LazyImageOptions = {
2 rootMargin?: string;
3 loadedClass?: string;
4};
5 
6export function initLazyImages(
7 container: ParentNode = document,
8 { rootMargin = '200px 0px', loadedClass = 'is-loaded' }: LazyImageOptions = {}
9): () => void {
10 const targets = container.querySelectorAll<HTMLImageElement>('img[data-src]');
11 
12 if (!('IntersectionObserver' in window)) {
13 targets.forEach((img) => loadImage(img, loadedClass));
14 return () => {};
15 }
16 
17 const observer = new IntersectionObserver((entries, obs) => {
18 for (const entry of entries) {
19 if (!entry.isIntersecting) continue;
20 loadImage(entry.target as HTMLImageElement, loadedClass);
21 obs.unobserve(entry.target);
22 }
23 }, { rootMargin, threshold: 0.01 });
24 
25 targets.forEach((img) => observer.observe(img));
26 
27 return () => observer.disconnect();
28}
29 
30function loadImage(img: HTMLImageElement, loadedClass: string): void {
31 const { src, srcset } = img.dataset;
32 if (!src) return;
33 
34 img.addEventListener('load', () => img.classList.add(loadedClass), { once: true });
35 
36 if (srcset) img.srcset = srcset;
37 img.src = src;
38 
39 delete img.dataset.src;
40 delete img.dataset.srcset;
41}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1IntersectionObserver lets you react to viewport proximity without manual scroll listeners.
  2. 2Feature-detect browser APIs and provide an eager fallback so nothing silently fails.
  3. 3Returning a cleanup function makes side-effecting initializers safe to tear down.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { DataSource } from 'typeorm';

Per-tenant database connections in NestJS

multi-tenancy connection-pooling dependency-injection
Advanced 8 steps

Share this explainer

Here's the card — post it anywhere.

Lazy-loading images with IntersectionObserver — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code