Lazy load

2 snippets across 2 stacks — HTML & CSS, JavaScript

HCHTML & CSS

Lazy Loading Images

HC · Images & Media
syntax
<img src="url" alt="description" loading="lazy">
example
<img src="/gallery/photo-42.jpg" alt="Sunset over the canyon" loading="lazy" width="600" height="400">

Note loading="lazy" defers loading until the image nears the viewport. Do not lazy-load images that are visible on initial load (above the fold) since it slows their appearance. Use loading="eager" (the default) for hero images.

JSJavaScript

Dynamic Import

JS · Modules
syntax
const module = await import("./module.js");
example
async function loadEditor() {
  const { EditorView } = await import("./editor.js");
  return new EditorView(document.getElementById("editor"));
}

// Conditional loading
if (needsCharting) {
  const { renderChart } = await import("./charts.js");
  renderChart(data);
}

Note Returns a promise that resolves to the module namespace. Ideal for code-splitting, lazy loading, and conditional imports. Works at runtime, not just at the top of a file.