边缘星云

返回

优化你的网站

提升网站性能和用户体验

集成工具#

本主题已集成以下工具:

CDN#

一些轻量级库使用JavaScript静态链接。你可以配置CDN链接来提升网站性能。

src/site.config.ts
export const theme: ThemeUserConfig = {
  // ...
  npmCDN: 'https://cdn.jsdelivr.net/npm'
  // 推荐:
  // - https://cdn.jsdelivr.net/npm
  // - https://cdn.smartcis.cn/npm
  // - https://unkpg.com
  // - https://cdn.cbd.int
}
ts

编码规范#

.astro文件中使用“类TypeScript”语法的注释是个好方法。这能确保你的注释不会被渲染到最终的生产环境HTML文件中。

---
// 这里是放置注释的安全位置
import { AstroComponent } from '@/components'
---

<div>
  <!-- 这是一种不好的注释风格,会保留在生产环境中 -->
  {/* 这是一种更好的注释风格 */}
  <AstroComponent>Hello, Astro!</AstroComponent>
</div>
astro

图片优化#

使用优化组件#

使用<Image />组件显示优化后的图片:使用内置的<Image /> Astro组件可展示以下内容的优化版本:

  • 位于src/文件夹内的本地图片
  • 来自授权源的已配置远程图片

<Image />可以转换本地或授权远程图片的尺寸、文件类型和质量,以便你控制显示的图片。生成的<img>标签包含alt、loading和decoding属性,并能自动推断图片尺寸,避免累积布局偏移(CLS)。

你可以使用loading="lazy"为图片启用懒加载。

src/pages/somepage.astro
---
// 导入Image组件和图片
import { Image } from 'astro:assets'

import myImage from '../assets/my_image.png' // 图片尺寸为1600x900
---

<!-- `alt`在Image组件中是必填项 -->
<Image src={myImage} alt='我的图片描述。' />
astro
<!-- 输出结果 -->
<img
  src="/_astro/my_image.hash.webp"
  width="1600"
  height="900"
  decoding="async"
  loading="lazy"
  class="my-class"
  alt=""
/>
html

使用这种方式,图片会被转换为WebP格式。.md.mdx文件默认启用此功能。

更改图片尺寸#

尽管本主题已集成了一些知名的图片优化插件,但对于首页等关键页面,你可能仍需优化图片。

一个简单的方法是使用在线工具(如TinyPNG)手动压缩图片。

适配外部图片#

如果你在使用外部图片,除了添加懒加载标签,还可以为其添加Astro预优化服务。这会将外部图片转换为本地优化后的图片。

astro.config.mjs
export default defineConfig({
  // ...
  image: {
    // ...
    domains: ['<具体的网站域名>'] 
  }
})
js