v0.6.22

Image Lazy Loading

Last updated


This page covers how :lazyload loads an image only when it enters the viewport, and which fallback image is used on failure.

Syntax


  1. <div id="app">
  2. <img :lazyload="photo" width="240" />
  3. <img :lazyload="photo" :effect="circle" width="240" />
  4. </div>
  5. <script>
  6. const app = new QUI({
  7. id: "app",
  8. data: { photo: "/static/image/cover.png" },
  9. });
  10. </script>
Live preview · @pardnchiu/quickui@0.6.22

StageBehavior
Initial rendersrc is set to a transparent placeholder; with :effect="circle" a spinning loader is used instead
Enters the viewportIntersectionObserver fires, sends HEAD then GET, and sets src to a blob URL
AfterwardsThe lazyload and effect attributes are removed
Later rendersAlready loaded images get src directly and are not observed again

<img> elements already on the page with a lazyload="url" attribute, even if QuickUI did not render them, are observed too when the listener is created.

Failure Handling


Casesrc
A TypeError with the message Load failed (Safari's CORS failure) or an image EventThe original URL is used directly
Any other error (including 404, and CORS failures in browsers with a different message such as Chrome)https://cdn.jsdelivr.net/gh/pardnchiu/PDRenderKit@latest/static/image/404.svg

For cross-origin images, make sure the server sends CORS headers, otherwise Chrome shows the 404 fallback.

Disabling


  1. new QUI({ id: "app", option: { lazyload: false } });

With it disabled, no listener is created; using :lazyload in the template then throws because the observer does not exist, so use :src instead.
中文