跪拜 Guibai
← Back to the summary

A Vue Directive That Lazy-Loads Only in View, With a Scroll Fallback

Performance Optimization: Lazy Loading Encapsulation in Vue.js

In modern front-end web applications, for the sake of user experience optimization, it is essential to apply lazy loading to content layout. Loading only the content currently visible in the viewport effectively reduces the number of resource requests and rendering tasks executed at once or within a short time, greatly improving overall page performance and the fluidity of user interactions.

Usually, in front-end JavaScript, lazy loading is implemented using the IntersectionObserver API to listen to node visibility, or falling back to scroll position checks for older browser kernels.

1. Necessity and Introduction to Lazy Loading

1.1 Common Scenarios

Image Lazy Loading

In daily web browsing, images are an indispensable part of rich content, but their loading has a significant impact on page speed. A typical modern image can easily exceed 1MB. If a page contains many images that need to be loaded simultaneously, the overall loading time increases due to network request concurrency, and could even lose users because of several seconds or tens of seconds of loading time. Therefore, to speed up pages with many images, images that are not yet in the viewport are not loaded initially; they are loaded only when the user scrolls and the image tag enters or is about to enter the viewport. This greatly improves the initial load performance.

Batching Delayed Requests, Calculations, Rendering, etc.

This is similar to the image scenario. For example, a page with many separate modules like charts or multiple data tables: we can use placeholder elements, and when the page or container scrolls to that content in the viewport, we initialize the complex logic, make API requests, or run rendering. This spreads out the initial high CPU usage from running everything at once, improving smoothness.


2. Underlying Implementation of Lazy Loading

2.1 DOM Node Visibility Listening

IntersectionObserver API: https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver

Basic usage:

var observer = new IntersectionObserver(callback[, options]);
observer.observe(el) // start observing a DOM node

This API asynchronously observes whether a specific DOM node is visible, so it can be used to decide when to load resources. Because the callback is async, it doesn't consume much of the browser's main thread, so performance is improved.

Then we consider compatibility. Although there are some compatibility issues, with modern mainstream browsers this is not a big problem.

Browser compatibility

So we first check for the API:

const hasIntersectionObserver = 'IntersectionObserver' in window

If it doesn't exist, we fall back to scroll logic, described in the next section.

Next, we implement and wrap IntersectionObserver to observe DOM nodes:

const addObserver = (el: any, callback: any) => {
  if (!el) {
    return null
  }

  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      // Check if it has entered the viewport
      if (('isIntersecting' in entry && !!entry.isIntersecting) || (entry.intersectionRatio > 0)) {
        callback()
        observer.unobserve(entry.target)
      }
    })
  })

  observer.observe(el)

  return () => {
    observer.disconnect()
    observer = null
  }
}

2.2 Container Scroll Detection

If IntersectionObserver is not supported, we fall back to scroll position checks:

Based on Attribute Calculations to Determine if a Node is Scrolled into the Container

1. Core Concepts

Example diagram:

offsetTop calculation example

2. Judging Logic Formulas

Assume we have computed the absolute top coordinate elementTop (i.e., parent.offsetTop + child.offsetTop), and element height elementHeight.

Horizontal scrolling is similar with scrollLeft, elementWidth, clientWidth.

Disadvantage: Every scroll triggers calculations, and reading properties like offsetTop causes browser "reflow", which can cause performance jank on complex pages.

Using getBoundingClientRect to Judge Visibility in Container

This is the most common method. This API returns the element's size and position relative to the viewport, skipping the complex offsetParent accumulation.

getBoundingClientRect position relations

Core Logic:

Example:

const isInContainer = (el: any, container: any) => {
  if (!el || !container) { return false }

  const elRect = el.getBoundingClientRect()
  const containerRect = container.getBoundingClientRect()

  return (
    // top of element is above bottom of container (entered viewport)
    elRect.top < containerRect.bottom &&
    // bottom of element is below top of container (not out of viewport)
    elRect.bottom > containerRect.top &&
    // same for horizontal
    elRect.right > containerRect.left &&
    elRect.left < containerRect.right
  )
}

Optimizing Scroll Listening with Throttling

Because scroll events fire at high frequency, without optimization, they cause drawing pressure and frame rate drops. Therefore, we throttle the scroll callbacks to save execution resources and performance.

Throttling is a common front-end optimization technique, not detailed here; for more, search or ask an AI. Since our project already includes lodash, we use _.throttle directly.

2.3 Vue.js Lazy Loading Encapsulation

The above logic is collected into a Vue directive. The business side only needs to write v-lazy without worrying about underlying visibility checks and fallback.

Relevant Encapsulation

const getStyle = (el: HTMLElement, style: string) => {
  return window.getComputedStyle(el).getPropertyValue(style)
}

The complete directive encapsulation is as follows, using IntersectionObserver when available and falling back to throttled scroll listening otherwise:

// directives/lazy.ts
import type { App, Directive, DirectiveBinding } from 'vue'

interface LazyOptions {
  src?: string
  container?: HTMLElement | null
  rootMargin?: string
  threshold?: number
  onLoad?: (el: HTMLElement) => void
}

const cleanupMap = new WeakMap<HTMLElement, () => void>()

const isVisible = (el: HTMLElement, container?: HTMLElement | null) => {
  const elRect = el.getBoundingClientRect()
  const containerRect = (container ?? document.documentElement).getBoundingClientRect()

  return (
    elRect.top < containerRect.bottom &&
    elRect.bottom > containerRect.top &&
    elRect.right > containerRect.left &&
    elRect.left < containerRect.right
  )
}

const lazy: Directive<HTMLElement, LazyOptions> = {
  mounted(el: HTMLElement, binding: DirectiveBinding<LazyOptions>) {
    const { src, container = null, rootMargin = '0px', threshold = 0, onLoad } = binding.value || {}

    const load = () => {
      if (el.dataset.lazyLoaded === 'true') return
      el.dataset.lazyLoaded = 'true'
      if (src) el.setAttribute('src', src)
      onLoad?.(el)
    }

    // Prefer IntersectionObserver
    if ('IntersectionObserver' in window) {
      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting || entry.intersectionRatio > 0) {
              load()
              observer.unobserve(entry.target)
            }
          })
        },
        { root: container, rootMargin, threshold },
      )

      observer.observe(el)
      cleanupMap.set(el, () => observer.disconnect())
      return
    }

    // Fallback: scroll listener + throttle
    const root = container ?? document.documentElement
    let timer: ReturnType<typeof setTimeout> | null = null

    const handler = () => {
      if (timer) return
      timer = setTimeout(() => {
        timer = null
        if (isVisible(el, container)) {
          load()
          root.removeEventListener('scroll', handler)
        }
      }, 200)
    }

    root.addEventListener('scroll', handler, { passive: true })
    cleanupMap.set(el, () => {
      if (timer) clearTimeout(timer)
      root.removeEventListener('scroll', handler)
    })
  },

  unmounted(el: HTMLElement) {
    cleanupMap.get(el)?.()
    cleanupMap.delete(el)
  },
}

export function installLazyDirective(app: App) {
  app.directive('lazy', lazy)
}

Usage in business code:

<template>
  <div class="image-list">
    <img v-lazy="{ src: item.url }" alt="" />
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { installLazyDirective } from '@/directives/lazy'

const app = useApp()
installLazyDirective(app)
</script>

Two points to note:


3. Summary

The essence of lazy loading is postponing resource loading until it is truly needed, thus reducing initial requests and rendering pressure:

  1. Detection layer: Prefer IntersectionObserver for async visibility checks, avoiding high-frequency scroll events and layout thrashing.
  2. Fallback layer: For older browsers, use getBoundingClientRect with throttled scroll listening to ensure functionality.
  3. Encapsulation layer: Put visibility checks, loading flags, and cleanup logic into a v-lazy directive so business code only cares about the resource URL.
  4. Benefits: Scenarios like images, charts, complex list modules show the clearest gains, with reduced initial bundle size and main-thread usage.

It's worth noting that lazy loading solves the "timing of rendering and requests" problem, not the problem of the resource itself being too large. If a single image is several MB, you still need to compress and convert formats (WebP/AVIF) and do responsive sizing; lazy loading is just the last line of defense.