=> 前端 0x43 // 前端开发

Astro 视图过渡与岛屿架构:交互性与性能兼得

F face 184 字 · 约 1 分钟 0 条评论 前端开发

Astro 最迷人的地方在于:默认零 JavaScript,但在需要交互的地方又能精准注水。配合视图过渡(View Transitions),页面切换可以达到接近 SPA 的丝滑感。

#岛屿架构

传统的 MPA 每次导航都要重新解析全部资源;Astro 的岛屿(Islands)让交互组件独立水合:

text
---
// 一个交互组件只在进入视口时才加载 JS
import SearchBox from '../components/SearchBox.astro';
---
<SearchBox client:visible />

#零依赖的客户端脚本

Astro 的 <script> 标签会被打包、去重并按需加载,用原生 API 就能实现大部分交互:

ts
// 目录高亮:IntersectionObserver 监听标题可见性
const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) activate(entry.target.id);
  }
}, { rootMargin: '-15% 0px -70% 0px' });

document.querySelectorAll('.md-body h2[id]').forEach((h) => observer.observe(h));

#实测数据

  • 首页 LCP 稳定在 0.4s 以内
  • 全站 JS 体积 < 30KB gzip
  • 把 TOC 滚动监听换成 CSS scroll driven animations
  • 试试浏览器原生的 View Transition API

性能优化的最高境界不是优化,而是从一开始就不发送多余的代码。

—— 某位前端工程师的碎碎念

本文链接:/post/astro-5-view-transitions/ · 转载请注明出处 · 原文由 Typecho 驱动

//评论 0

还没有评论,来说两句吧~

$ 发表评论 visitor@astro-5-view-transitions

// 相关阅读