vue实现延迟加载
Vue 实现延迟加载的方法
路由懒加载
Vue Router 支持动态导入组件,实现路由级别的懒加载。使用 import() 语法动态导入组件,Webpack 会自动将懒加载的组件分离成单独的代码块。
const routes = [
{
path: '/lazy',
component: () => import('./views/LazyComponent.vue')
}
]
组件懒加载
使用 Vue 的 defineAsyncComponent 方法可以实现组件级别的懒加载。适用于非路由组件或按需加载的组件。

import { defineAsyncComponent } from 'vue'
const AsyncComponent = defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
)
图片懒加载
通过 Intersection Observer API 或第三方库实现图片的延迟加载,减少初始页面加载时间。
// 使用 Intersection Observer
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)
})
动态导入第三方库
对于大型第三方库,可以使用动态导入在需要时加载。

// 按需加载 moment.js
const formatDate = async (date) => {
const moment = await import('moment')
return moment.default(date).format('YYYY-MM-DD')
}
骨架屏技术
在懒加载内容完成前显示占位内容,提升用户体验。
<template>
<div v-if="loading">Loading skeleton...</div>
<LazyComponent v-else />
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { defineAsyncComponent } from 'vue'
const loading = ref(true)
const LazyComponent = defineAsyncComponent({
loader: () => import('./LazyComponent.vue'),
loadingComponent: LoadingSpinner,
delay: 200
})
onMounted(() => {
setTimeout(() => loading.value = false, 1000)
})
</script>
预加载策略
对于可能很快需要的资源,可以使用 preload 或 prefetch 提示浏览器提前加载。
<link rel="preload" href="lazy-component.js" as="script">
这些方法可以单独使用或组合使用,根据具体场景选择最适合的延迟加载方案。路由懒加载适合SPA应用,组件懒加载适合大型组件,图片懒加载优化媒体资源加载,动态导入减少初始包大小,骨架屏改善用户体验。






