面试题答案
一键面试实现图片延迟加载的方式
- 使用
next/image
组件:- 引入组件:在 Next.js 项目中,
next/image
组件是官方提供的处理图片的组件,它默认支持延迟加载。首先在页面中引入该组件:
import Image from 'next/image';
- 使用方式:假设项目中有一个图片文件
example.jpg
,放在public
目录下,使用如下:
const MyComponent = () => { return ( <div> <Image src="/example.jpg" alt="Example Image" width={300} height={200} /> </div> ); };
- 配置参数:
src
:指定图片的路径,相对路径是相对于public
目录。alt
:图片的替代文本,用于无障碍访问。width
和height
:设置图片的宽度和高度,这两个属性是必须的,用于在图片加载前预留空间,避免布局跳动。
- 引入组件:在 Next.js 项目中,
- 自定义延迟加载逻辑(较少用,可作为拓展思路):
- 使用
IntersectionObserver
API:虽然next/image
已经满足大部分需求,但也可以手动实现。首先创建一个自定义组件,例如LazyImage.js
:
import { useState, useEffect } from'react'; const LazyImage = ({ src, alt, width, height }) => { const [isVisible, setIsVisible] = useState(false); useEffect(() => { const observer = new IntersectionObserver((entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { setIsVisible(true); observer.unobserve(entry.target); } }); }); const imgElement = document.createElement('img'); imgElement.src = src; imgElement.alt = alt; imgElement.width = width; imgElement.height = height; observer.observe(imgElement); return () => { observer.disconnect(); }; }, [src, alt, width, height]); return isVisible? ( <img src={src} alt={alt} width={width} height={height} /> ) : null; }; export default LazyImage;
- 使用方式:在页面中引入
LazyImage
组件:
import LazyImage from './LazyImage'; const MyPage = () => { return ( <div> <LazyImage src="/example.jpg" alt="Example Image" width={300} height={200} /> </div> ); }; export default MyPage;
- 使用
延迟加载对性能提升的作用原理
- 减少初始加载负担:页面加载时,只加载当前视口内或即将进入视口的图片,而不是一次性加载页面上所有图片。这使得初始页面加载的资源量大幅减少,从而加快页面的首次渲染时间(First Contentful Paint,FCP),提升用户体验。
- 优化带宽利用:对于用户可能永远不会看到的图片(例如位于页面底部,用户未滚动到的区域),不会浪费带宽进行加载。这对于移动设备或网络带宽有限的用户来说,尤为重要,能节省用户的数据流量,同时也减少了服务器的负载。
- 避免阻塞渲染:图片资源加载可能会阻塞页面的渲染。延迟加载确保图片不会在页面关键渲染路径上造成阻塞,使得页面的 HTML、CSS 和关键 JavaScript 能够更快地加载和渲染,提高页面的可交互性(Time to Interactive,TTI)。