js如何实现按需加载
按需加载的实现方法
按需加载(Lazy Loading)是一种优化技术,用于延迟加载资源,直到它们真正需要时才加载。在 JavaScript 中,可以通过多种方式实现按需加载。
动态导入(Dynamic Import)
使用 ES6 的动态导入语法,可以在运行时按需加载模块。动态导入返回一个 Promise,可以在需要时解析模块。
// 示例:动态导入模块
button.addEventListener('click', async () => {
const module = await import('./module.js');
module.doSomething();
});
动态导入适用于现代浏览器和构建工具(如 Webpack、Rollup),能够自动拆分代码为独立的 chunk。
Webpack 的代码分割
Webpack 支持通过动态导入自动实现代码分割,生成独立的文件块(chunks)。
// Webpack 会自动识别动态导入并拆分代码
const loadModule = async () => {
const { default: component } = await import('./Component');
return component;
};
配置 Webpack 的 output.chunkFilename 可以自定义生成的 chunk 文件名。
懒加载路由(React/Vue)
在单页应用(SPA)中,路由级别的懒加载可以显著提升初始加载速度。

React 示例:
import { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
Vue 示例:
const LazyComponent = () => import('./LazyComponent.vue');
const router = new VueRouter({
routes: [{ path: '/lazy', component: LazyComponent }],
});
图片和资源的懒加载
对于图片或其他资源,可以使用 IntersectionObserver 或 loading="lazy" 属性实现懒加载。

IntersectionObserver 示例:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
observer.observe(img);
});
HTML 原生懒加载:
<img src="placeholder.jpg" data-src="actual-image.jpg" loading="lazy">
第三方库支持
一些库(如 loadjs 或 lazysizes)可以简化按需加载的实现。
loadjs 示例:
loadjs(['/path/to/script.js'], 'scriptBundle');
loadjs.ready('scriptBundle', () => {
console.log('Script loaded');
});
注意事项
- 动态导入和代码分割需要构建工具支持(如 Webpack、Vite)。
- 懒加载可能导致短暂的延迟,需合理设计加载状态(如 Suspense 的 fallback)。
- 对于关键资源,避免过度懒加载以免影响用户体验。






