barba-js

barba-js

熱門

用於建立網站頁面間流暢、順暢轉場效果的頁面轉場函式庫。當需要實作頁面轉場、打造類 SPA 體驗、新增動畫路由切換或建置具備順暢導覽體驗的網站時,請使用此 Skill。於涉及 Barba.js、頁面轉場、路由設定、檢視 (view) 管理、轉場 Hook、GSAP 整合或流暢頁面導覽等任務時觸發。支援配合 gsap-scrolltrigger 來實現轉場動畫。

768星標
128分支
更新於 2025/11/20
SKILL.md
唯讀
名稱
barba-js
描述

用於建立網站頁面間流暢、順暢轉場效果的頁面轉場函式庫。當需要實作頁面轉場、打造類 SPA 體驗、新增動畫路由切換或建置具備順暢導覽體驗的網站時,請使用此 Skill。於涉及 Barba.js、頁面轉場、路由設定、檢視 (view) 管理、轉場 Hook、GSAP 整合或流暢頁面導覽等任務時觸發。支援配合 gsap-scrolltrigger 來實現轉場動畫。

Barba.js

現代化頁面轉場函式庫,用於打造網站頁面之間流暢且順暢的轉場效果。Barba.js 透過攔截頁面導覽並在不進行整頁重新載入的情況下管理轉場,讓多頁式網站(MPA)擁有如同單頁應用程式(SPA)般的使用體驗。

概述 (Overview)

Barba.js 是一款輕量級(壓縮後僅約 7kb)的 JavaScript 函式庫。它能攔截頁面間的導覽行為、透過 AJAX 擷取新內容,並在舊容器與新容器之間進行順暢的轉場。在保有傳統多頁式架構優點的同時,有效減少頁面載入延遲與 HTTP 請求次數。

核心功能:

  • 無需整頁重新載入即可實現順暢的頁面轉場
  • 完整的生命週期 Hook,精準掌控轉場各階段
  • 基於 View 的邏輯,實現各頁面專屬的行為
  • 內建路由支援(搭配 @barba/router 擴充套件)
  • 具備高度可擴充性的擴充套件系統
  • 檔案小巧且具備極佳效能
  • 框架無關(Framework-agnostic,可搭配原生 JS、GSAP、anime.js 等使用)

核心概念 (Core Concepts)

1. Wrapper、Container 與 Namespace

Barba.js 使用特定的 DOM 結構來管理轉場:

HTML 結構:

<body data-barba="wrapper">
  <!-- 靜態元素(如 header、nav)保留在 container 外面 -->
  <header>
    <nav>
      <a href="/">Home</a>
      <a href="/about">About</a>
    </nav>
  </header>

  <!-- 動態內容放入 container -->
  <main data-barba="container" data-barba-namespace="home">
    <!-- 這部分的內容會在導覽時更換 -->
    <h1>Home Page</h1>
    <p>Content that will transition out...</p>
  </main>

  <!-- 靜態 footer 保留在 container 外面 -->
  <footer>© 2025</footer>
</body>

三大關鍵元素:

  1. Wrapper (data-barba="wrapper")

    • 最外層的容器
    • 位於 Wrapper 內部但在 Container 之外的所有元素都會持續保留
    • 非常適合放置不需要更換的 Header、導覽列與 Footer
  2. Container (data-barba="container")

    • 動態內容區域,會在頁面切換時更新
    • 轉場期間只有此區塊會被替換
    • 每個頁面都必須包含此標籤
  3. Namespace (data-barba-namespace="home")

    • 每個頁面類型的唯一識別碼
    • 用於轉場規則與 View 邏輯中
    • 例如:"home", "about", "product", "blog-post"

2. 轉場生命週期 (Transition Lifecycle)

Barba.js 每次導覽均遵循精準的生命週期:

預設非同步流程 (Default Async Flow):

  1. 使用者點擊連結
  2. Barba 攔截導覽行為
  3. 預先抓取下一頁(透過 AJAX)
  4. 快取新內容
  5. Leave hook - 執行當前頁面淡出/離場動畫
  6. 等待 Leave 動態完成
  7. 移除舊 Container,插入新 Container
  8. Enter hook - 執行新頁面淡入/進場動畫
  9. 等待 Enter 動畫完成
  10. 更新瀏覽器歷史紀錄 (History API)

同步流程 (Sync Flow)(設定 sync: true):

  1. 使用者點擊連結
  2. Barba 攔截導覽行為
  3. 預先抓取下一頁
  4. 等待新頁面載入完成
  5. Leave 與 Enter hooks 同時執行(交叉淡入淡出效果 Crossfade)
  6. 替換 Container
  7. 更新瀏覽器歷史紀錄

3. Hooks

Barba 提供 11 個生命週期 Hook 來控制轉場:

Hook 執行順序:

首次載入頁面:
  beforeOnce → once → afterOnce

每次導覽:
  before → beforeLeave → leave → afterLeave →
  beforeEnter → enter → afterEnter → after

Hook 類型:

  • 全域 Hook (Global hooks):每次轉場皆會執行 (barba.hooks.before())
  • 轉場 Hook (Transition hooks):定義於特定轉場物件內部
  • View Hook:定義於 View 物件內部,用於處理單一頁面專屬邏輯

常見 Hook 使用情境:

  • beforeLeave - 重設捲動位置、準備動畫
  • leave - 執行當前頁面離場動畫
  • afterLeave - 清理舊頁面資源
  • beforeEnter - 準備新頁面(隱藏元素、設定初始狀態)
  • enter - 執行新頁面進場動畫
  • afterEnter - 初始化新頁面的指令碼、追蹤 Analytics 數據

4. Views

Views 是以 Namespace 為基礎執行的單一頁面專屬邏輯容器:

barba.init({
  views: [{
    namespace: 'home',
    beforeEnter() {
      // 首頁專屬設定
      console.log('Entering home page');
    },
    afterEnter() {
      // 初始化首頁功能
      initHomeSlider();
    }
  }, {
    namespace: 'product',
    beforeEnter() {
      console.log('Entering product page');
    },
    afterEnter() {
      initProductGallery();
    }
  }]
});

常見模式 (Common Patterns)

1. 基礎設定

安裝方式:

npm install --save-dev @barba/core
# 或
yarn add @barba/core --dev

最簡設定:

import barba from '@barba/core';

barba.init({
  transitions: [{
    name: 'default',
    leave({ current }) {
      // 淡出當前頁面
      return gsap.to(current.container, {
        opacity: 0,
        duration: 0.5
      });
    },
    enter({ next }) {
      // 淡入新頁面
      return gsap.from(next.container, {
        opacity: 0,
        duration: 0.5
      });
    }
  }]
});

2. 淡入淡出轉場(非同步 Async)

經典的淡出後淡入轉場:

import barba from '@barba/core';
import gsap from 'gsap';

barba.init({
  transitions: [{
    name: 'fade',
    async leave({ current }) {
      await gsap.to(current.container, {
        opacity: 0,
        duration: 0.5,
        ease: 'power2.inOut'
      });
    },
    async enter({ next }) {
      // 初始設為透明
      gsap.set(next.container, { opacity: 0 });

      // 淡入
      await gsap.to(next.container, {
        opacity: 1,
        duration: 0.5,
        ease: 'power2.inOut'
      });
    }
  }]
});

3. 交叉淡入淡出轉場(同步 Sync)

新舊頁面同時進行淡入與淡出:

barba.init({
  transitions: [{
    name: 'crossfade',
    sync: true, // 開啟同步模式
    leave({ current }) {
      return gsap.to(current.container, {
        opacity: 0,
        duration: 0.8,
        ease: 'power2.inOut'
      });
    },
    enter({ next }) {
      return gsap.from(next.container, {
        opacity: 0,
        duration: 0.8,
        ease: 'power2.inOut'
      });
    }
  }]
});

4. 具備重疊效果的滑動轉場 (Slide Transition)

舊頁面滑出、新頁面滑入,並帶有重疊效果:

barba.init({
  transitions: [{
    name: 'slide',
    sync: true,
    leave({ current }) {
      return gsap.to(current.container, {
        x: '-100%',
        duration: 0.7,
        ease: 'power3.inOut'
      });
    },
    enter({ next }) {
      // 初始定位於螢幕右側外
      gsap.set(next.container, { x: '100%' });

      // 從右側滑入
      return gsap.to(next.container, {
        x: '0%',
        duration: 0.7,
        ease: 'power3.inOut'
      });
    }
  }]
});

5. 轉場規則(條件式轉場)

根據導覽情境定義不同的轉場效果:

barba.init({
  transitions: [
    // 從首頁到任何頁面:淡入淡出
    {
      name: 'from-home-fade',
      from: { namespace: 'home' },
      leave({ current }) {
        return gsap.to(current.container, {
          opacity: 0,
          duration: 0.5
        });
      },
      enter({ next }) {
        return gsap.from(next.container, {
          opacity: 0,
          duration: 0.5
        });
      }
    },
    // 產品頁到產品頁:向左滑動
    {
      name: 'product-to-product',
      from: { namespace: 'product' },
      to: { namespace: 'product' },
      leave({ current }) {
        return gsap.to(current.container, {
          x: '-100%',
          duration: 0.6
        });
      },
      enter({ next }) {
        gsap.set(next.container, { x: '100%' });
        return gsap.to(next.container, {
          x: '0%',
          duration: 0.6
        });
      }
    },
    // 預設後備轉場 (Default fallback)
    {
      name: 'default',
      leave({ current }) {
        return gsap.to(current.container, {
          opacity: 0,
          duration: 0.3
        });
      },
      enter({ next }) {
        return gsap.from(next.container, {
          opacity: 0,
          duration: 0.3
        });
      }
    }
  ]
});

6. 使用 Router 擴充套件進行基於路由的轉場

使用 @barba/router 設定特定路由的轉場:

安裝方式:

npm install --save-dev @barba/router

使用範例:

import barba from '@barba/core';
import barbaPrefetch from '@barba/prefetch';
import barbaRouter from '@barba/router';

// 定義路由
barbaRouter.init({
  routes: [
    { path: '/', name: 'home' },
    { path: '/about', name: 'about' },
    { path: '/products/:id', name: 'product' }, // 動態片段
    { path: '/blog/:category/:slug', name: 'blog-post' }
  ]
});

barba.use(barbaRouter);
barba.use(barbaPrefetch); // 可選:在懸停時預抓取

barba.init({
  transitions: [{
    name: 'product-transition',
    to: { route: 'product' }, // 觸發於特定路由名稱
    leave({ current }) {
      return gsap.to(current.container, {
        scale: 0.95,
        opacity: 0,
        duration: 0.5
      });
    },
    enter({ next }) {
      return gsap.from(next.container, {
        scale: 1.05,
        opacity: 0,
        duration: 0.5
      });
    }
  }]
});

7. 載入指示器 (Loading Indicator)

在擷取頁面內容期間顯示載入狀態:

barba.init({
  transitions: [{
    async leave({ current }) {
      // 顯示 Loader
      const loader = document.querySelector('.loader');
      gsap.set(loader, { display: 'flex', opacity: 0 });
      gsap.to(loader, { opacity: 1, duration: 0.3 });

      // 淡出頁面
      await gsap.to(current.container, {
        opacity: 0,
        duration: 0.5
      });
    },
    async enter({ next }) {
      // 隱藏 Loader
      const loader = document.querySelector('.loader');
      await gsap.to(loader, { opacity: 0, duration: 0.3 });
      gsap.set(loader, { display: 'none' });

      // 淡入新頁面
      await gsap.from(next.container, {
        opacity: 0,
        duration: 0.5
      });
    }
  }]
});

整合模式 (Integration Patterns)

GSAP 整合

Barba.js 可與 GSAP 無縫搭配進行動畫製作:

基於 Timeline 的轉場:

import barba from '@barba/core';
import gsap from 'gsap';

barba.init({
  transitions: [{
    async leave({ current }) {
      const tl = gsap.timeline();

      tl.to(current.container.querySelector('h1'), {
        y: -50,
        opacity: 0,
        duration: 0.3
      })
      .to(current.container.querySelector('.content'), {
        y: -30,
        opacity: 0,
        duration: 0.3
      }, '-=0.2')
      .to(current.container, {
        opacity: 0,
        duration: 0.2
      });

      await tl.play();
    },
    async enter({ next }) {
      const tl = gsap.timeline();

      // 設定初始狀態
      gsap.set(next.container, { opacity: 0 });
      gsap.set(next.container.querySelector('h1'), { y: 50, opacity: 0 });
      gsap.set(next.container.querySelector('.content'), { y: 30, opacity: 0 });

      tl.to(next.container, {
        opacity: 1,
        duration: 0.2
      })
      .to(next.container.querySelector('h1'), {
        y: 0,
        opacity: 1,
        duration: 0.5,
        ease: 'power3.out'
      })
      .to(next.container.querySelector('.content'), {
        y: 0,
        opacity: 1,
        duration: 0.5,
        ease: 'power3.out'
      }, '-=0.3');

      await tl.play();
    }
  }]
});

進階 GSAP 整合模式請參閱 gsap-scrolltrigger skill。

頁面專屬初始化 (View-Specific Initialization)

針對每個頁面分別初始化函式庫或指令碼:

barba.init({
  views: [
    {
      namespace: 'home',
      afterEnter() {
        // 初始化首頁功能
        initHomepageSlider();
        initParallaxEffects();
      },
      beforeLeave() {
        // 清理資源
        destroyHomepageSlider();
      }
    },
    {
      namespace: 'gallery',
      afterEnter() {
        initLightbox();
        initMasonry();
      },
      beforeLeave() {
        destroyLightbox();
      }
    }
  ]
});

Analytics 數據追蹤

在頁面切換時追蹤 Page View:

barba.hooks.after(() => {
  // Google Analytics
  if (typeof gtag !== 'undefined') {
    gtag('config', 'GA_MEASUREMENT_ID', {
      page_path: window.location.pathname
    });
  }

  // 或使用 Data Layer
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'pageview',
    page: window.location.pathname
  });
});

第三方指令碼重新初始化

在頁面轉場完成後重新執行第三方工具指令碼:

barba.hooks.after(() => {
  // 重新初始化第三方 Widget
  if (typeof twttr !== 'undefined') {
    twttr.widgets.load(); // Twitter 小工具
  }

  if (typeof FB !== 'undefined') {
    FB.XFBML.parse(); // Facebook 小工具
  }

  // 重新執行語法高亮
  if (typeof Prism !== 'undefined') {
    Prism.highlightAll();
  }
});

效能最佳化 (Performance Optimization)

1. 預先抓取 (Prefetching)

使用 @barba/prefetch 在使用者滑鼠懸停於連結時提前載入頁面:

npm install --save-dev @barba/prefetch
import barba from '@barba/core';
import barbaPrefetch from '@barba/prefetch';

barba.use(barbaPrefetch);

barba.init({
  // 預設於滑鼠懸停在連結上時觸發預抓取
  prefetch: {
    root: null, // 監聽所有連結
    timeout: 3000 // 快取過期時間 (毫秒)
  }
});

2. 避免版面躍動 (Prevent Layout Shift)

設定 Container 的最小高度以避免內容突然跳動:

[data-barba="container"] {
  min-height: 100vh;
  /* 或使用視埠高度扣除 header/footer */
  min-height: calc(100vh - 80px - 60px);
}

3. 動畫效能最佳化

儘量使用支援 GPU 硬體加速的屬性:

// ✅ 建議做法 - 支援 GPU 加速
gsap.to(element, {
  opacity: 0,
  x: -100,
  scale: 0.9,
  rotation: 45
});

// ❌ 應避免 - 會引發 reflow/repaint
gsap.to(element, {
  width: '50%',
  height: '300px',
  top: '100px'
});

4. 清理事件監聽器 (Clean Up Event Listeners)

在 beforeLeave 或 View 的 Hook 中移除監聽器:

barba.init({
  views: [{
    namespace: 'home',
    afterEnter() {
      // 新增監聽器
      this.clickHandler = () => console.log('clicked');
      document.querySelector('.btn').addEventListener('click', this.clickHandler);
    },
    beforeLeave() {
      // 移除監聽器
      document.querySelector('.btn').removeEventListener('click', this.clickHandler);
    }
  }]
});

5. 圖片延遲載入 (Lazy Load Images)

將圖片載入延後至轉場完成後:

barba.init({
  transitions: [{
    async enter({ next }) {
      // 先完成轉場動畫
      await gsap.from(next.container, {
        opacity: 0,
        duration: 0.5
      });

      // 轉場完成後再載入圖片
      const images = next.container.querySelectorAll('img[data-src]');
      images.forEach(img => {
        img.src = img.dataset.src;
        img.removeAttribute('data-src');
      });
    }
  }]
});

常見陷阱 (Common Pitfalls)

1. 忘記回傳 Promise

問題:動畫尚未執行完畢,轉場就瞬間結束。

解決方案:務必回傳 Promise 或搭配 async/await:

// ❌ 錯誤 - 動畫已開始但不會等待它完成
leave({ current }) {
  gsap.to(current.container, { opacity: 0, duration: 0.5 });
}

// ✅ 正確 - 回傳 promise
leave({ current }) {
  return gsap.to(current.container, { opacity: 0, duration: 0.5 });
}

// ✅ 同樣正確 - 使用 async/await
async leave({ current }) {
  await gsap.to(current.container, { opacity: 0, duration: 0.5 });
}

2. 未排除特定的預設連結行為

問題:部分連結仍會引發整頁重新載入。

解決方案:Barba 預設會自動阻止站內連結的預設行為,但可能需要排除外部連結:

barba.init({
  prevent: ({ href }) => {
    // 允許外部連結正常開啟
    if (href.indexOf('http') > -1 && href.indexOf(window.location.host) === -1) {
      return true;
    }
    return false;
  }
});

3. 跨頁面 CSS 樣式衝突

問題:轉場期間,舊頁面的 CSS 影響到了新頁面的版面配置。

解決方案:使用基於 Namespace 的 CSS 選擇器,或在轉場時重設樣式:

/* 搭配 Namespace 的專屬樣式 */
[data-barba-namespace="home"] .hero {
  background: blue;
}

[data-barba-namespace="about"] .hero {
  background: red;
}

或在 beforeEnter 中進行重設:

beforeEnter({ next }) {
  // 重設捲動位置
  window.scrollTo(0, 0);

  // 重設全域狀態
  document.body.classList.remove('menu-open');
}

4. 未更新 Document Title 與 Meta 標籤

問題:切換頁面後,網頁標題 (Title) 與 Meta 標籤沒有隨之更新。

解決方案:使用 @barba/head 擴充套件或手動進行更新:

npm install --save-dev @barba/head
import barba from '@barba/core';
import barbaHead from '@barba/head';

barba.use(barbaHead);

barba.init({
  // Head 擴充套件會自動更新 <head> 內的標籤
});

或透過手動更新:

barba.hooks.after(({ next }) => {
  // 更新標題
  document.title = next.html.querySelector('title').textContent;

  // 更新 Meta 標籤
  const newMeta = next.html.querySelectorAll('meta');
  newMeta.forEach(meta => {
    const name = meta.getAttribute('name') || meta.getAttribute('property');
    if (name) {
      const existing = document.querySelector(`meta[name="${name}"], meta[property="${name}"]`);
      if (existing) {
        existing.setAttribute('content', meta.getAttribute('content'));
      }
    }
  });
});

5. Enter 階段出現畫面閃爍 (Animation Flicker)

問題:在進場動畫開始前,新頁面短暫閃爍並顯示。

解決方案:在 CSS 中或在 beforeEnter 設定初始隱藏狀態:

/* CSS 作法 */
[data-barba="container"] {
  opacity: 0;
}

[data-barba="container"].is-visible {
  opacity: 1;
}
// JavaScript 作法
beforeEnter({ next }) {
  gsap.set(next.container, { opacity: 0 });
}

6. 同步轉場(Sync)缺少正確定位

問題:同步轉場時,由於 Container 上下堆疊導致版面產生錯位與位移。

解決方案:在轉場期間將 Container 設定為絕對定位 (Absolute Positioning):

[data-barba="wrapper"] {
  position: relative;
}

[data-barba="container"] {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}

或使用 JavaScript 進行動態控制:

barba.init({
  transitions: [{
    sync: true,
    beforeLeave({ current }) {
      gsap.set(current.container, {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%'
      });
    }
  }]
});

相關資源 (Resources)

本 Skill 包含以下內容:

scripts/

可用於常見 Barba.js 工作流程的可執行工具:

  • transition_generator.py - 產生轉場效果模板程式碼
  • project_setup.py - 初始化 Barba.js 專案結構

references/

詳細技術文件:

  • api_reference.md - 完整的 Barba.js API 文件(包含 hooks, transitions, views, router)
  • hooks_guide.md - 完整 11 個 Hook 的執行順序與使用情境範例
  • gsap_integration.md - 用於 Barba 轉場的 GSAP 動畫整合模式
  • transition_patterns.md - 常見轉場效果實作指南

assets/

範本與入門專案:

  • starter_barba/ - 完整的 Barba.js + GSAP 專案入門範本
  • examples/ - 實際應用情境的轉場效果實作專案

相關 Skills (Related Skills)

  • gsap-scrolltrigger - 用於轉場中更進階的高級 GSAP 捲動動畫
  • locomotive-scroll - 可與 Barba 結合使用,打造跨頁面的平滑捲動 (Smooth Scroll) 體驗
  • motion-framer - 用於 React 頁面轉場的另一種替代解決方案