图片懒加载
图片懒加载是一种网页优化技术,用于延迟加载页面中的图片,以减少页面加载时间和带宽消耗。在网页中,当用户滚动浏览页面时,只有当图片进入可视窗口时才加载图片,而不是一次性加载所有图片
思路:通过JavaScript监听滚动事件,当图片进入可视窗口时再动态加载图片。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| document.addEventListener('DOMContentLoaded', function() { let lazyImages = document.querySelectorAll('.lazy-load');
function lazyLoad() { lazyImages.forEach(img => { if (img.getBoundingClientRect().top < window.innerHeight && img.getAttribute('data-src')) { img.src = img.getAttribute('data-src'); img.removeAttribute('data-src'); } }); }
window.addEventListener('scroll', lazyLoad); window.addEventListener('resize', lazyLoad);
lazyLoad(); });
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <template> <div ref="imageRef"> <img v-if="isVisible" :src="imageSrc" alt="Lazy Loaded Image"> </div> </template>
<script setup> import { ref, onMounted } from 'vue';
export default { setup() { const imageSrc = 'image.jpg'; // 图片的真实URL const isVisible = ref(false); // 控制图片是否显示的变量
const imageRef = ref(null); // 图片元素的引用
// 创建 Intersection Observer 实例 const intersectionObserver = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { isVisible.value = true; // 图片进入可视区域时显示图片 intersectionObserver.unobserve(imageRef.value); // 停止观察图片元素 } }); });
// 在组件挂载后开始观察图片元素 onMounted(() => { intersectionObserver.observe(imageRef.value); });
} }; </script>
|