<!-- 预连接关键域名 -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<!-- 预加载关键资源 -->
<link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>
<!-- 异步加载非关键 JS -->
<script src="analytics.js" async></script>
<!-- 延迟加载不影响首屏的 JS -->
<script src="widget.js" defer></script>
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="图片" loading="lazy">
</picture>
<!-- 指定尺寸避免 CLS -->
<img src="photo.jpg" width="800" height="600" alt="图片">
/* 只动画 transform 和 opacity(GPU 加速) */
.box {
transition: transform 0.3s, opacity 0.3s;
will-change: transform;
}
/* 避免动画 width、height、top、left(触发重排) */
# Nginx 缓存配置
# 静态资源:强缓存
location ~* \.(js|css|png|jpg|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# HTML 文件:协商缓存
location ~* \.html$ {
add_header Cache-Control "no-cache";
}
# 开启 Gzip/Brotli
gzip on;
gzip_types text/plain text/css application/json application/javascript;
server {
listen 80;
server_name apimp.cn;
root /var/www/apimp.cn;
gzip on;
gzip_types text/html text/css application/javascript;
location ~* \.(js|css|png|jpg|svg|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
# 预留 API 接口转发
# location /api/ {
# proxy_pass http://127.0.0.1:3000;
# }
}
前端性能优化涵盖加载、渲染、网络三个层面。核心思路:减少资源体积、减少请求次数、减少渲染阻塞、利用浏览器缓存。