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.

Frequently asked questions

How does HTML & CSS handle lazy load?
This task is covered in 2 stacks on this page: HTML & CSS, JavaScript. The "Lazy Loading Images" snippet in HTML & CSS uses `<img src="url" alt="description" loading="lazy">`.
Which code does the HTML & CSS example use?
The "Lazy Loading Images" snippet uses `<img src="url" alt="description" loading="lazy">`, from the Images & Media section of the HTML & CSS cheat sheet.
Which stacks cover "lazy load" on this page?
HTML & CSS, JavaScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Lazy Loading Images": 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.