Implementing Lazy Loading for Frontend Performance Optimization
This article explains the concept of lazy loading in front‑end development, covering placement of placeholder elements, scroll event listening, viewport detection methods, detailed JavaScript implementations, and advanced optimizations such as throttling, vertical‑only checks, and extending lazy loading to other resource types.
1. Introduction
When optimizing a system solely from a front‑end perspective, the methods are limited to improving first‑screen rendering speed, such as lazy loading images, static resources, or delaying API calls to give the first screen maximum performance space.
2. Implementation Idea
1) Resource Placeholder
During lazy loading, a placeholder is set by defining the image width and height and using a
<img class="qLazy" data-original='https://xyz.abc.com/common/logo.png'/>tag without the src attribute, preventing immediate download.
<img class="qLazy" data-original='https://xyz.abc.com/common/logo.png'/>2) Listening to scroll events
The lazy‑load container is usually the scrolling area; on mobile long lists the default container is the window object.
3) Determining if a resource is in the viewport
The core of lazy loading is to load a resource only when it is about to appear in the viewport, ensuring the user sees a fully loaded element.
4) Loading the resource or executing callbacks
The loader can be extended beyond images to scripts, styles, or custom callbacks. Below is a simplified lazy‑load implementation:
function QLazyLoader(setting) {
var _setting = {
selector: '.qLazy',
event: 'scroll',
container: setting.container || window,
attribute: 'data-original',
loadtype: 'img',
appear: null,
load: null
};
// ... (scroll listener, element checks, load actions)
}3. How to Determine if an Element Is in the Viewport
1) Using viewport height, scroll offset, and element offset
function isElementInViewport(el) {
var offsetTop = el.offsetTop;
var clientHeight = document.documentElement.clientHeight;
var scrollTop = document.documentElement.scrollTop;
if (clientHeight + scrollTop > offsetTop) {
console.log("already in viewport");
} else {
console.log("not in viewport");
}
}2) Using getBoundingClientRect API
This API returns a DOMRect with top, left, bottom, right, width, and height values relative to the viewport.
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (document.documentElement.clientWidth || document.documentElement.clientHeight) &&
rect.right <= (document.documentElement.clientWidth || document.documentElement.clientHeight)
);
}3) IntersectionObserver API
Provides an asynchronous way to observe when a target element intersects the viewport. Example template:
function query(selector) {
return Array.from(document.querySelectorAll(selector));
}
var observer = new IntersectionObserver(function(changes) {
changes.forEach(function(change) {
var container = change.target;
var content = container.querySelector('template').content;
container.appendChild(content);
observer.unobserve(container);
});
});
query('.lazy-loaded').forEach(function(item) {
observer.observe(item);
});4. Extensions and Optimizations
1) Adding throttling
Throttle the scroll handler to reduce frequent DOM calculations and prevent UI jank.
if (_setting.throttleMS > 0) {
this.update = throttle(this.update, _setting.throttleMS);
}2) Vertical‑only checks
Skip horizontal calculations when only vertical scrolling matters.
if (setting.vertical) {
if (jqThis.height() <= 0 || jqThis.css('display') === 'none') return;
// vertical visibility logic
}3) Extending to other resource types
Lazy loading can be applied to JS, CSS, video, audio, or custom callbacks by configuring the loader accordingly.
5. Conclusion
Lazy loading is a versatile front‑end optimization technique that improves perceived performance, but it introduces viewport detection overhead and potential event‑binding complexities. Use it judiciously, especially when page resources are few, as a full‑page load may sometimes provide a better user experience.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
