正文图片优化的核心是“按需选择格式与尺寸”。通过 `Accept` 协商 AVIF/WebP 与 `Sec-CH-DPR/Width` 客户端提示,可在边缘决定最佳变体并投递,显著降低字节量与提升画质。
一、中间件启用 Client Hintsimport { NextResponse } from 'next/server'
export function middleware() {
const res = NextResponse.next()
res.headers.set('Accept-CH', 'DPR, Width')
return res
}
二、路由处理图片协商export const runtime = 'edge'
function pickFormat(accept: string) {
const a = accept || ''
if (a.includes('image/avif')) return { ext: 'avif', type: 'image/avif' }
if (a.includes('image/webp')) return { ext: 'webp', type: 'image/webp' }
return { ext: 'jpg', type: 'image/jpeg' }
}
function pickWidth(widthHint: string | null) {
const w = Number(widthHint || '0')
const candidates = [320, 640, 750, 828, 1080, 1200, 1920]
const target = candidates.find((x) => w && x >= w) || 1200
return target
}
export async function GET(req: Request) {
const url = new URL(req.url)
const accept = req.headers.get('accept') || ''
const dpr = Number(req.headers.get('sec-ch-dpr') || '1')
const widthHint = req.headers.get('sec-ch-width')
const fmt = pickFormat(accept)
const width = pickWidth(widthHint)
const effective = Math.max(1, Math.min(3, dpr))
const finalWidth = Math.round(width * effective)
const key = url.searchParams.get('key') || 'hero'
const cdn = `https://cdn.example.com/images/${key}-${finalWidth}.${fmt.ext}`
const r = await fetch(cdn)
return new Response(r.body, {
headers: {
'Content-Type': fmt.type,
'Cache-Control': 'public, s-maxage=86400, max-age=600, immutable',
'Vary': 'Accept, DPR, Width',
'Accept-CH': 'DPR, Width'
}
})
}
三、治理要点Vary 管理:对 `Accept/DPR/Width` 设置 `Vary`,避免跨设备与浏览器格式互相污染缓存。尺寸候选:列出合理候选宽度并按提示向上取整,防止过多变体导致缓存碎片化。最终宽度:乘以 `DPR` 提升高密屏清晰度,同时限制最大值避免资源浪费。

发表评论 取消回复