图片777
八、图片显示优化 问题让你优化图片显示你怎么优化 // 1. 格式选择 // WebP AVIF JPEG/PNG // WebP比JPEG小25-35%比PNG小80% // 2. 响应式图片 img srcimage-800.jpg srcset image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w sizes (max-width: 500px) 400px, (max-width: 900px) 800px, 1200px // 3. 懒加载 img loadinglazy srcimage.jpg // 4. 渐进式加载 function ProgressiveImage({ src, placeholder }) { const [currentSrc, setCurrentSrc] useState(placeholder) useEffect(() { const img new Image() img.src src img.onload () setCurrentSrc(src) }, [src]) return ( img src{currentSrc} style{{ filter: currentSrc placeholder ? blur(10px) : none }} / ) } // 5. 使用CDN // 加上图片处理参数 https://cdn.example.com/image.jpg?w800q75formatwebp // 6. 缓存策略 // 强缓存 hash文件名 Cache-Control: max-age31536000 // image-8f3c9d.jpg // 7. 预加载关键图片 link relpreload asimage hrefhero.jpg // 8. 使用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) } }) }) 九、WebP兼容性降级 问题webp格式的图片有兼容性问题吗怎么做降级处理 // 1. picture标签最推荐 picture source srcsetimage.webp typeimage/webp source srcsetimage.jp2 typeimage/jp2 img srcimage.jpg altfallback /picture // 2. 特性检测 function supportsWebP() { const canvas document.createElement(canvas) if (canvas.toDataURL) { return canvas.toDataURL(image/webp).indexOf(image/webp) 0 } return false } // 使用 const src supportsWebP() ? image.webp : image.jpg // 3. 服务端检测 app.get(/image, (req, res) { const accept req.headers[accept] if (accept accept.includes(image/webp)) { res.setHeader(Content-Type, image/webp) res.sendFile(image.webp) } else { res.sendFile(image.jpg) } }) // 4. Modernizr if (Modernizr.webp) { // 使用WebP } else { // 使用降级格式 } // 5. Next.js自动处理 Image src/image.jpg / // 自动检测Accept头返回对应格式 // 6. 批量转换工具 // 构建时生成webp版本 const imagemin require(imagemin) const imageminWebp require(imagemin-webp) await imagemin([images/*.{jpg,png}], { destination: public/images, plugins: [imageminWebp({ quality: 75 })] }) // 7. 动态加载 const webpSupported await checkWebPSupport() const imageUrl webpSupported ? /img.webp : /img.jpg 原文链接https://blog.csdn.net/weixin_50077637/article/details/158740098