Skip to content

Instantly share code, notes, and snippets.

@tcaptan-cr
Created November 22, 2023 07:35
Show Gist options
  • Save tcaptan-cr/bf0ac25f77cb6b6c58c916e6577d91c3 to your computer and use it in GitHub Desktop.
Save tcaptan-cr/bf0ac25f77cb6b6c58c916e6577d91c3 to your computer and use it in GitHub Desktop.
Lazy Load Scroll Margin Explainer

Lazy Load Scroll Margin Explainer

Changes the lazy load intersection observer's init dictionary to use a scrollMargin instead of a rootMargin.

This allows lazy loading images contained inside CSS scrollers, like carousels, to load as expected when near the viewport instead of the current behavior where these images load when at least one pixel is intersecting the viewport.

Lazy Load Scroll Margin Specification

Problem

Developers would like to use lazy loading for images inside possibly nested scroll containers like carousels.

Currently the lazy load intersection observer is set up using a rootMargin. This does not work well for pages that use images in CSS scrollers, like carousels, causing the images to load too late, when they become visible and the intersection with the root is detected. To work around this issue some developers are choosing to not use lazy loading, thus increasing the overall bandwidth usage for their sites.

This problem was discussed in github issue 431.

Proposed Solution

Using scrollMargin for the lazy load intersection observer will allow lazy loading images in scrollers to load when they are near the viewport as expected.

Code Example

<style>
  #scroller {
    width: 100px;
    height: 100px;
    overflow: scroll;
    background-color: gray;
  }

  #spacer {
    width: 100px;
    height: 100px;
  }

  #target {
    width: 100px;
    height: 100px;
  }
</style>

<div id="scroller">
  <div id="spacer"></div>
  <img
    id="target"
    src="images/dog.png"
    loading="lazy"
    onload="img_onload();"
  >
</div>

<script>
  function img_onload() {
    console.log("Image has loaded.");
  }
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment