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
callback: called when the target enters or exits the root element or when its visible proportion exceeds the threshold. It receives:entries: an array of IntersectionObserverEntry objects, each triggered threshold has some deviation from the specified thresholdobserver: the IntersectionObserver instance that is triggered
options(optional): configures the observer. If not specified, the document viewport is used as root, no margin, and threshold is 0% (any pixel change triggers the callback). You can specifyroot,rootMargin,threshold.
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.
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:
- Pass the node to observe and use it
- Call the callback when the node enters the viewport
- Return a function to cancel listening and destroy the observer
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
document.documentElement.clientHeight: the height of the browser's visible areadocument.documentElement.scrollTop: the vertical scroll distance of the document (the hidden top part)- Bottom coordinate of visible area:
scrollTop+clientHeight. If an element's top coordinate is less than this, the element has appeared from the bottom. offsetToppitfall:offsetTopis the distance from the element to its nearest positioned ancestor (relative/absolute/fixed).- In the diagram,
parent: position: relative;is highlighted, meaningchild.offsetTopis only the distance to the parent, not to the document top. - To get the true Y coordinate in the document, you need to sum up:
child absolute Y = child.offsetTop + parent.offsetTop
Example diagram:
2. Judging Logic Formulas
Assume we have computed the absolute top coordinate elementTop (i.e., parent.offsetTop + child.offsetTop), and element height elementHeight.
- Just entered viewport (from bottom):
elementTop < (scrollTop + clientHeight) - Completely within viewport:
(elementTop >= scrollTop) && ((elementTop + elementHeight) <= (scrollTop + clientHeight)) - Scrolled out of viewport (from top):
(elementTop + elementHeight) < scrollTop
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 MDN: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
Core Logic:
- If the element's relative top is less than the container's relative bottom, the element has scrolled into the container (entered viewport).
- If the element's relative bottom is greater than the container's relative top, the element hasn't scrolled above the container (not yet out of viewport).
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
_.throttledirectly.
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:
- Load only once: The
lazyLoadedflag ensures the same node won't be triggered repeatedly. - Timely cleanup: The
unmountedhook disconnects the observer and removes scroll listeners, avoiding listener leaks in long lists.
3. Summary
The essence of lazy loading is postponing resource loading until it is truly needed, thus reducing initial requests and rendering pressure:
- Detection layer: Prefer
IntersectionObserverfor async visibility checks, avoiding high-frequency scroll events and layout thrashing. - Fallback layer: For older browsers, use
getBoundingClientRectwith throttled scroll listening to ensure functionality. - Encapsulation layer: Put visibility checks, loading flags, and cleanup logic into a
v-lazydirective so business code only cares about the resource URL. - 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.