前言
- Hey, 我是 Immerse
- 文章首發於個人部落格【https://yaolifeng.com】,更多內容請關注個人部落格
- 轉載說明:轉載請在文章頭部註明原文出處及版權宣告!
起因
- 最近上線了個人部落格,片段頁面存在大量圖片,在圖片載入方面體驗很差,可以說是斷崖式,從 0-1 完全沒有任何過渡(這很影響頁面佈局和使用者體驗,對於設定了圖片寬高的圖片還好,如果沒設定,就會有一個圖片撐高的過程)
巧合
- 在準備寫這篇文章當天前端南玖大佬發表了一篇文章,我直呼大資料牛逼 👍🏻文章: 點選檢視
這篇文章我們將討論其他幾種方案,閒話少說,言歸正傳。
對於常規的圖片最佳化這裡不在贅述,大致如下:
- 壓縮圖片、使用 CSS sprites、懶載入、預載入、CDN 快取、合適的圖片格式、七牛 CDN 圖片引數等等
探索
以下是這篇文章提到的幾種方案(因為個人專案基於 Next,所以有些示例程式碼是 React)
- (1)使用圖片主色調
- (2)使用某個顏色
- (3)使用圖片的縮圖
- (4)使用模糊 + 壓縮圖片
- (5)圖片佔位符
方案 1:使用圖片主色調
- 在日常開發中,我們的圖片
src
可能是動態的,也就是一個字串string
url, 當我們指定了placeholder="blur"
時,還必須新增blurDataURL
屬性,
import Image from 'next/image';
// Pixel GIF code adapted from https://stackoverflow.com/a/33919020/266535
const keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const triplet = (e1: number, e2: number, e3: number) =>
keyStr.charAt(e1 >> 2) +
keyStr.charAt(((e1 & 3) << 4) | (e2 >> 4)) +
keyStr.charAt(((e2 & 15) << 2) | (e3 >> 6)) +
keyStr.charAt(e3 & 63);
const rgbDataURL = (r: number, g: number, b: number) =>
`data:image/gif;base64,R0lGODlhAQABAPAA${
triplet(0, r, g) + triplet(b, 255, 255)
}/yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==`;
const Color = () => (
<div>
<h1>Image Component With Color Data URL</h1>
<Image
alt="Dog"
src="/dog.jpg"
placeholder="blur"
blurDataURL={rgbDataURL(237, 181, 6)}
width={750}
height={1000}
style={{
maxWidth: '100%',
height: 'auto'
}}
/>
<Image
alt="Cat"
src="/cat.jpg"
placeholder="blur"
blurDataURL={rgbDataURL(2, 129, 210)}
width={750}
height={1000}
style={{
maxWidth: '100%',
height: 'auto'
}}
/>
</div>
);
export default Color;
方案 2:使用某個顏色
- 在
next.config.js
中配置placeholder
為color
,然後使用backgroundColor
屬性
// next.config.js
module.exports = {
images: {
placeholder: 'color',
backgroundColor: '#121212'
}
};
// 使用
<Image src="/path/to/image.jpg" alt="image title" width={500} height={500} placeholder="color" />
方案 3: 使用圖片的縮圖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>漸進式圖片載入</title>
<style>
.placeholder {
background-color: #f6f6f6;
background-size: cover;
background-repeat: no-repeat;
position: relative;
overflow: hidden;
}
.placeholder img {
position: absolute;
opacity: 0;
top: 0;
left: 0;
width: 100%;
transition: opacity 1s linear;
}
.placeholder img.loaded {
opacity: 1;
}
.img-small {
filter: blur(50px);
transform: scale(1);
}
</style>
</head>
<body>
<div
class="placeholder"
data-large="https://qncdn.mopic.mozigu.net/work/143/24/42b204ae3ade4f38/1_sg-uLNm73whmdOgKlrQdZA.jpg"
>
<img
src="https://qncdn.mopic.mozigu.net/work/143/24/5307e9778a944f93/1_sg-uLNm73whmdOgKlrQdZA.jpg"
class="img-small"
/>
<div style="padding-bottom: 66.6%"></div>
</div>
</body>
</html>
<script>
window.onload = function () {
var placeholder = document.querySelector('.placeholder'),
small = placeholder.querySelector('.img-small');
// 1. 顯示小圖並載入
var img = new Image();
img.src = small.src;
img.onload = function () {
small.classList.add('loaded');
};
// 2. 載入大圖
var imgLarge = new Image();
imgLarge.src = placeholder.dataset.large;
imgLarge.onload = function () {
imgLarge.classList.add('loaded');
};
placeholder.appendChild(imgLarge);
};
</script>
方案 4:使用模糊+壓縮圖片
// progressive-image.tsx
'use client';
import React, { useState, useEffect } from 'react';
import imageCompression from 'browser-image-compression';
interface ProgressiveImageProps {
src: string;
alt?: string;
width?: number;
height?: number;
layout?: 'fixed' | 'responsive' | 'fill' | 'intrinsic';
className?: string;
style?: React.CSSProperties;
}
export const ProgressiveImage: React.FC<ProgressiveImageProps> = ({
src,
alt = '',
width,
height,
layout = 'responsive',
className = '',
style = {}
}) => {
const [currentSrc, setCurrentSrc] = useState<string>(src);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [blurLevel, setBlurLevel] = useState<number>(20);
useEffect(() => {
let isMounted = true;
const loadImage = async () => {
try {
// 載入並壓縮原始圖片
const response = await fetch(src);
const blob = await response.blob();
// 生成低質量預覽圖
const tinyOptions = {
maxSizeMB: 0.0002,
maxWidthOrHeight: 16,
useWebWorker: true,
initialQuality: 0.1
};
const tinyBlob = await imageCompression(blob, tinyOptions);
if (isMounted) {
const tinyUrl = URL.createObjectURL(tinyBlob);
setCurrentSrc(tinyUrl);
// 開始逐漸減小模糊度
startSmoothTransition();
}
// 載入原始圖片
const highQualityImage = new Image();
highQualityImage.src = src;
highQualityImage.onload = () => {
if (isMounted) {
setCurrentSrc(src);
// 當高質量圖片載入完成時,繼續平滑過渡
setTimeout(() => {
setIsLoading(false);
}, 100);
}
};
} catch (error) {
console.error('Error loading image:', error);
if (isMounted) {
setCurrentSrc(src);
setIsLoading(false);
}
}
};
const startSmoothTransition = () => {
// 從20px的模糊逐漸過渡到10px
const startBlur = 20;
const endBlur = 10;
const duration = 1000; // 1秒
const steps = 20;
const stepDuration = duration / steps;
const blurStep = (startBlur - endBlur) / steps;
let currentStep = 0;
const interval = setInterval(() => {
if (currentStep < steps && isMounted) {
setBlurLevel(startBlur - blurStep * currentStep);
currentStep++;
} else {
clearInterval(interval);
}
}, stepDuration);
};
setIsLoading(true);
setBlurLevel(20);
loadImage();
return () => {
isMounted = false;
if (currentSrc && currentSrc.startsWith('blob:')) {
URL.revokeObjectURL(currentSrc);
}
};
}, [src]);
const getContainerStyle = (): React.CSSProperties => {
const baseStyle: React.CSSProperties = {
position: 'relative',
overflow: 'hidden'
};
switch (layout) {
case 'responsive':
return {
...baseStyle,
maxWidth: width || '100%',
width: '100%'
};
case 'fixed':
return {
...baseStyle,
width: width,
height: height
};
case 'fill':
return {
...baseStyle,
width: '100%',
height: '100%',
position: 'absolute',
top: 0,
left: 0
};
case 'intrinsic':
return {
...baseStyle,
maxWidth: width,
width: '100%'
};
default:
return baseStyle;
}
};
const getImageStyle = (): React.CSSProperties => {
const baseStyle: React.CSSProperties = {
filter: isLoading ? `blur(${blurLevel}px)` : 'none',
transition: 'filter 0.8s ease-in-out', // 增加過渡時間
transform: 'scale(1.1)', // 稍微放大防止模糊時出現邊緣
...style
};
switch (layout) {
case 'responsive':
return {
...baseStyle,
width: '100%',
height: 'auto',
display: 'block'
};
case 'fixed':
return {
...baseStyle,
width: width,
height: height
};
case 'fill':
return {
...baseStyle,
width: '100%',
height: '100%',
objectFit: 'cover'
};
case 'intrinsic':
return {
...baseStyle,
width: '100%',
height: 'auto'
};
default:
return baseStyle;
}
};
return (
<div className={`${className}`} style={getContainerStyle()}>
{currentSrc && <img src={currentSrc} alt={alt} style={getImageStyle()} />}
</div>
);
};
// 使用
<ProgressiveImage
src={photo}
alt={short.title}
width={300}
height={250}
layout="responsive"
className="h-full min-h-[150px]"
/>
方案 5:圖片佔位符
Next.js 的 next/image 元件
placeholder
屬性提供了個選項blur
,預設為empty
blur
會生成一個模糊的預覽影像(但這個選項會增加初始載入實踐,因為需要時間去生成模糊圖片)- 注意:如果
placeholder="blur"
時,必須使用import
靜態引入圖片的方式,這樣 Next.js 才會對圖片進行漸進式載入的預處理
import Image from 'next/image';
import mountains from '/public/mountains.jpg';
const PlaceholderBlur = () => (
<div>
<h1>Image Component With Placeholder Blur</h1>
<Image
alt="Mountains"
src={mountains}
placeholder="blur"
width={700}
height={475}
style={{
maxWidth: '100%',
height: 'auto'
}}
/>
</div>
);
export default PlaceholderBlur;
總結
- 產品第一印象很重要,良好的使用者體驗對於產品來說是必需的。
- 感謝閱讀,我們下次再見!