Web component / Examples

<lazy-img>

This component creates optional images based on container size, viewport size, or scroll position. Use native images for essential content. See the README for installation and API documentation.

Basic Example

Set src and alt for an optional image. With no conditions, the component creates its image when it upgrades. Without JavaScript, it creates no image.

For ordinary offscreen images, native <img loading="lazy"> lets the browser defer requests without custom-element registration. lazy-img adds conditions before creating an image; it’s not a replacement for essential native images.

Basic Usage

<lazy-img
  src="./sample.svg"
  alt="Mountain trail at sunrise illustration">
</lazy-img>

Container Query Example (Default)

Set min-inline-size to wait for the parent’s content-box inline size. The default query type is container. If the parent never reaches that size, the component doesn’t create the image.

Try it: Each container below starts smaller than needed. Use its labeled width slider (arrow keys, Home, and End), or drag the resize handle (bottom-right corner), to widen the container and watch the image lazy load when it hits the threshold. On narrow screens, the available space may be below that threshold; use a wider window.

Small Container (min-inline-size: 300px)

Widen this container to 300px to create the image. It starts at 200px. Once created, the image remains if you shrink the container again.

<lazy-img
  src="./sample.svg"
  alt="Mountain trail at sunrise illustration"
  min-inline-size="300">
</lazy-img>
📏 Current width: 200px / Min: 300px

Medium Container (min-inline-size: 500px)

👉 Widen this container to 500px to trigger the image load.

<lazy-img
  src="./sample.svg"
  alt="Mountain trail at sunrise illustration"
  min-inline-size="500">
</lazy-img>
📏 Current width: 350px / Min: 500px

Media Query Example

Set query="media" to check window width instead of container size. This image waits for a viewport at least 768px wide. Shrinking the viewport afterward doesn’t unload the image or cancel its request.

Try it: Resize your browser window to see the effect. The image loads when the viewport reaches 768px wide.

Viewport Width Check (min-inline-size: 768px)

<lazy-img
  src="./sample.svg"
  alt="Mountain trail at sunrise illustration"
  min-inline-size="768"
  query="media">
</lazy-img>

Current viewport width: px

View Mode (Scroll-Based Loading)

Set query="view" to create the image after an intersecting IntersectionObserver notification. The observer measures the host’s box. View mode ignores size conditions and doesn’t set qualifies.

Try it: Scroll down to see images load as they enter the viewport. The timing can be controlled with view-range-start.

The current callback checks intersection, not the visibility ratio. Examples sharing observer settings can also trigger each other. The settings below aren’t a guarantee of per-image request timing. See the view-mode reference.

Basic View Mode (default: entry 0%)

The default setting uses a zero intersection threshold. After creation, the image remains when it leaves the viewport.

<lazy-img
  src="./sample.svg"
  alt="Mountain trail at sunrise illustration"
  query="view">
</lazy-img>

👇 Scroll down to see the image below load

Image not requested yet (requires JavaScript).

Threshold-Based (entry 50%)

Set view-range-start="entry 50%" to configure a 50% observer threshold. The callback can still create the image on an earlier intersecting notification.

<lazy-img
  src="./sample.svg"
  alt="Mountain trail at sunrise illustration"
  query="view"
  view-range-start="entry 50%">
</lazy-img>

👇 Scroll toward the image to observe creation

Image not requested yet (requires JavaScript).

Preload Before Visible (entry -200px)

Set view-range-start="entry -200px" to expand the observer’s bottom margin by 200px.

<lazy-img
  src="./sample.svg"
  alt="Mountain trail at sunrise illustration"
  query="view"
  view-range-start="entry -200px">
</lazy-img>

👇 The observer includes 200px below the viewport

Image not requested yet (requires JavaScript).

Responsive Images with srcset and sizes

Pass srcset and sizes to the created image so the browser can select a source.

srcset with sizes

👉 Widen this container to 400px to load the responsive image. Once loaded, the browser chooses the appropriate size from srcset.

<lazy-img
  src="./sample.svg"
  srcset="./sample-small.svg 400w,
          ./sample.svg 800w,
          ./sample-large.svg 1200w"
  sizes="(max-width: 600px) 400px,
         (max-width: 1000px) 800px,
         1200px"
  alt="Mountain trail at sunrise illustration"
  min-inline-size="400">
</lazy-img>
📏 Current width: 300px / Min: 400px

Named Breakpoints (CSS Custom Property)

Use the --lazy-img-mq CSS custom property on :root to define named breakpoints. Set different values at different media queries, and images will load when the breakpoint name matches.

Example with Named Breakpoints

This demo sets --lazy-img-mq via CSS media queries. Try resizing your browser window to see different breakpoint values.

<style>
  :root:has(body[data-demo-example="index"]) {
    --lazy-img-mq: small;
  }
  @media (min-width: 768px) {
    :root:has(body[data-demo-example="index"]) {
      --lazy-img-mq: medium;
    }
  }
  @media (min-width: 1024px) {
    :root:has(body[data-demo-example="index"]) {
      --lazy-img-mq: large;
    }
  }
</style>

<lazy-img
  src="./sample.svg"
  alt="Mountain trail at sunrise illustration"
  named-breakpoints="medium, large"
  query="media">
</lazy-img>

Current breakpoint: small

Image loads when breakpoint is "medium" or "large" (viewport ≥ 768px)

Events

The component dispatches a lazy-img:loaded event when it creates the image and a request can begin. This event does not confirm that the image downloaded or decoded. A native loading="lazy" hint can defer the fetch further.

Event Example

👉 Widen this container to 350px to trigger the load event.

<lazy-img
  id="event-demo"
  src="./sample.svg"
  alt="Mountain trail at sunrise illustration"
  min-inline-size="350">
</lazy-img>

<script>
document.getElementById('event-demo')
  .addEventListener('lazy-img:loaded', (e) => {
    console.log('Image created; request may begin:', e.detail.src);
  });
</script>
📏 Current width: 250px / Min: 350px

Event status: waiting for a request (requires JavaScript).

State Attributes

The component provides two boolean attributes to track state: loaded (has the component created its image?) and qualifies (does it currently meet conditions to show?). These allow you to control visibility with CSS.

Controlling Visibility

Widen this container to 400px, then shrink it. This example’s CSS hides the created image when it no longer qualifies; it doesn’t unload it. Don’t apply this rule to view-mode images, which don’t receive qualifies.

<style>
  /* Hide created images that don't qualify in this example */
  #state-demo-container lazy-img[loaded]:not([qualifies]) {
    display: none;
  }

</style>

<div id="state-demo-container">
  <lazy-img
    src="./sample.svg"
    alt="Mountain trail at sunrise illustration"
    min-inline-size="400">
  </lazy-img>
</div>
📏 Current width: 300px / Min: 400px
State: Not requested; requires JavaScript to check conditions.

Optional image download failure

Optional images can fail to download even after loaded is set. This intentionally missing image keeps an authored description and recovery link available.

<lazy-img src="./missing-image.jpg"
  alt="Mountain trail at sunrise"></lazy-img>
<p>If the image is unavailable:
  mountain trail at sunrise.
  <a href="./sample.svg">Open an alternative image</a>.
</p>

If the image is unavailable: mountain trail at sunrise. Open an alternative image.

Essential image without JavaScript

Use a native img for essential content rather than relying on custom-element enhancement. This separate example loads with or without JavaScript; its description and recovery link remain available if the image fails.

<figure>
  <img src="./sample.svg" width="800" height="400"
    alt="A mountain trail at sunrise, shown as a simple illustration" />
  <figcaption>This essential image works without JavaScript.</figcaption>
</figure>
<p>If the image is unavailable: mountain trail at sunrise.
  <a href="./sample.svg">Open an alternative image</a>.
</p>
A mountain trail at sunrise, shown as a simple illustration
This essential image works without JavaScript.

If the image is unavailable: mountain trail at sunrise. Open an alternative image.

API Reference

For complete documentation of attributes, events, and browser support, see the README.