🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Astro GSAP: Timelines, ScrollTrigger and Clean Setup

Astro GSAP setup that holds up: install gsap, register ScrollTrigger and SplitText, scope with gsap.context, respect reduced motion and survive the ClientRouter.

#Astro#GSAP#Animation#ScrollTrigger#JavaScript

To use GSAP in Astro, run npm install gsap, import gsap and any plugins such as ScrollTrigger in a <script> tag inside an .astro component, call gsap.registerPlugin(), and write your animations. Astro bundles the script as a module, so there’s no integration to add and no UI framework required. The parts that need care are scoping, reduced motion and cleanup when you use <ClientRouter />.

This guide covers an Astro GSAP setup from a first tween to scroll-driven sections, with the patterns that stop animations leaking between pages.

Key Takeaways

  • GSAP runs in plain Astro <script> tags; Astro deduplicates the script however many times the component renders.
  • GSAP and all its plugins, including ScrollTrigger and SplitText, have been free to use since 2025.
  • Wrap each component’s animations in gsap.matchMedia() or gsap.context() so you can revert them in one call.
  • With <ClientRouter />, set up on astro:page-load and revert on astro:before-swap.
  • Don’t hide content in CSS waiting for GSAP; set the starting state from JavaScript.

Why GSAP with Astro

Astro ships zero JavaScript by default, and most motion on a content site can stay in CSS. GSAP earns its place when you need things CSS makes awkward: sequenced timelines, pinned sections, scroll-scrubbed animation, text split into lines and characters, SVG path animation, or precise control over playback.

GSAP is framework-agnostic. It animates DOM elements, so it fits Astro’s model of static HTML plus small scripts better than libraries built around a component runtime. You don’t need an island or client:* directive unless the animated element is already inside a React, Vue or Svelte component. If you’re still deciding between libraries, our Astro animation comparison sets GSAP against CSS, Motion and Lottie.

Install GSAP

# terminal
npm install gsap

The gsap package includes the core and every plugin. Import plugins from their own paths, such as gsap/ScrollTrigger, so only what you use gets bundled.

Your first GSAP animation in Astro

---
// src/components/Hero.astro
---
<section class="hero">
  <h1 class="hero-title">Static pages, finished faster</h1>
  <p class="hero-copy">Ship HTML first and add motion where it helps.</p>
  <a class="hero-cta" href="/themes/">Browse themes</a>
</section>

<script>
  import { gsap } from 'gsap';

  const tl = gsap.timeline({ defaults: { ease: 'power2.out', duration: 0.6 } });
  tl.from('.hero-title', { y: 40, autoAlpha: 0 })
    .from('.hero-copy', { y: 20, autoAlpha: 0 }, '-=0.35')
    .from('.hero-cta', { scale: 0.9, autoAlpha: 0 }, '-=0.3');
</script>

A few Astro-specific notes:

  • Scripts are modules. Astro processes and bundles the <script>, which means it’s deferred and runs after the HTML is parsed. Your selectors will find their elements.
  • One copy per page. Render <Hero /> three times and the script is still included once. Write selectors that handle several instances, or scope them (next section).
  • Use autoAlpha rather than opacity. It also toggles visibility, so invisible elements can’t be focused or clicked mid-animation.

Scope animations with gsap.context and matchMedia

Global selectors like .hero-title are fine for a one-off hero. For components that appear several times, or anything you’ll need to clean up, scope the animation to the component’s root element.

gsap.matchMedia() does scoping and reduced motion in one place. Animations created inside add() run only while the media query matches, and GSAP reverts them automatically if it stops matching:

---
// src/components/FeatureList.astro
const { items } = Astro.props;
---
<ul class="features" data-features>
  {items.map((item: string) => <li class="feature">{item}</li>)}
</ul>

<script>
  import { gsap } from 'gsap';

  document.querySelectorAll<HTMLElement>('[data-features]').forEach((root) => {
    const mm = gsap.matchMedia(root);
    mm.add('(prefers-reduced-motion: no-preference)', () => {
      gsap.from('.feature', { y: 16, autoAlpha: 0, stagger: 0.08, duration: 0.4 });
    });
  });
</script>

Passing root as the scope means .feature resolves only inside that list. Users who ask for reduced motion get the content immediately, with no tween at all.

If you don’t need a media query, gsap.context(() => { ... }, root) gives the same scoping and returns an object with revert(), which undoes every tween and ScrollTrigger created inside it.

ScrollTrigger in Astro

ScrollTrigger ties animations to scroll position: reveal on entry, scrub with the scrollbar, or pin a section while its content animates.

---
// src/components/Steps.astro
---
<section class="steps" data-steps>
  <div class="steps-pin">
    <h2>How it works</h2>
    <ol>
      <li class="step">Pick a theme</li>
      <li class="step">Edit the content files</li>
      <li class="step">Deploy the dist folder</li>
    </ol>
  </div>
</section>

<script>
  import { gsap } from 'gsap';
  import { ScrollTrigger } from 'gsap/ScrollTrigger';

  gsap.registerPlugin(ScrollTrigger);

  document.querySelectorAll<HTMLElement>('[data-steps]').forEach((root) => {
    const mm = gsap.matchMedia(root);
    mm.add('(prefers-reduced-motion: no-preference) and (min-width: 768px)', () => {
      gsap.timeline({
        scrollTrigger: {
          trigger: root,
          start: 'top top',
          end: '+=150%',
          pin: '.steps-pin',
          scrub: true,
        },
      }).from('.step', { x: -60, autoAlpha: 0, stagger: 0.5 });
    });
  });
</script>

The media query also limits pinning to wider screens, where pinned sections behave better. Two things commonly go wrong with ScrollTrigger on Astro pages:

  1. Images without dimensions. ScrollTrigger measures positions when it’s created. If images above the trigger load later and push content down, the start and end points are wrong. Astro’s <Image /> component writes width and height, which prevents this; for other late layout changes, call ScrollTrigger.refresh().
  2. Web fonts swapping in. A font swap can change text height. Refresh after document.fonts.ready resolves if your pinned sections are text-heavy.

Split text with SplitText

SplitText used to be a members-only plugin and now ships in the free package. It wraps lines, words or characters in elements you can animate:

// src/scripts/split-heading.ts
import { gsap } from 'gsap';
import { SplitText } from 'gsap/SplitText';

gsap.registerPlugin(SplitText);

document.querySelectorAll<HTMLElement>('[data-split]').forEach((el) => {
  const split = SplitText.create(el, { type: 'lines, words' });
  gsap.from(split.words, { y: '100%', autoAlpha: 0, stagger: 0.04, duration: 0.5 });
});

Import the file from a component’s script with import '../scripts/split-heading.ts';. Split headings are more work for screen readers when each word becomes its own element, so check the SplitText documentation for its current accessibility options and test the result.

GSAP and the ClientRouter

With <ClientRouter />, Astro swaps page content instead of loading a new document. Bundled scripts run once, on the first page, so top-level GSAP code won’t run for pages you navigate to, and ScrollTriggers from the old page keep listening to scroll against elements that no longer exist.

The fix is one setup function and one cleanup:

// src/scripts/animations.ts
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

let mm: gsap.MatchMedia | undefined;

document.addEventListener('astro:page-load', () => {
  mm = gsap.matchMedia();
  mm.add('(prefers-reduced-motion: no-preference)', () => {
    gsap.utils.toArray<HTMLElement>('[data-reveal]').forEach((el) => {
      gsap.from(el, {
        y: 24,
        autoAlpha: 0,
        duration: 0.5,
        scrollTrigger: { trigger: el, start: 'top 85%' },
      });
    });
  });
});

document.addEventListener('astro:before-swap', () => {
  mm?.revert();
});

Import it once from your base layout:

---
// src/layouts/BaseLayout.astro
import { ClientRouter } from 'astro:transitions';
---
<html lang="en">
  <head>
    <ClientRouter />
  </head>
  <body>
    <slot />
    <script>
      import '../scripts/animations.ts';
    </script>
  </body>
</html>

astro:page-load fires on the first load and after every navigation, so this also works without the router. mm.revert() kills every tween and ScrollTrigger created inside it. Without the router, a full page load clears everything anyway. The Astro view transitions guide explains the full event order.

GSAP inside framework islands

If the animated element lives inside a React island, use the useGSAP() hook from @gsap/react, which handles context and cleanup for React’s lifecycle. Inside Vue or Svelte islands, create a gsap.context() when the component mounts and call revert() when it unmounts. Prefer plain .astro components where you can: a static component with a GSAP script ships GSAP, while an island ships GSAP plus the framework. Our island or script guide walks through that choice.

Avoid the flash before GSAP runs

A gsap.from() animation starts from a hidden state, but the module script runs only after the HTML has been parsed and possibly painted. Users can see the content flash before it disappears and animates in.

The tempting fix, opacity: 0 in CSS, is risky: if the script fails or is blocked, content stays invisible. Gate the hidden state on JavaScript instead:

---
// src/layouts/BaseLayout.astro (in <head>)
---
<script is:inline>
  document.documentElement.classList.add('js');
</script>
<style is:global>
  .js [data-reveal] { visibility: hidden; }
</style>

GSAP’s autoAlpha sets visibility: inherit when it animates the element in. For reduced motion, add a rule that keeps [data-reveal] visible, or call gsap.set('[data-reveal]', { autoAlpha: 1 }) in the reduced-motion branch of matchMedia().

Performance checklist for Astro GSAP

  • Import GSAP only in components that animate. A component’s script is included only on pages that render that component.
  • Animate transform and opacity (x, y, scale, rotation, autoAlpha). Animating width, height or top forces layout on every frame.
  • Don’t animate the largest image or heading on load if you care about Largest Contentful Paint; see fixing LCP in Astro.
  • Pair with Lenis only if you need smooth scrolling. If you do, feed Lenis’s scroll event to ScrollTrigger.update and drive Lenis from gsap.ticker so both share one frame loop.

Komal themes keep their default motion in CSS so they ship without client JavaScript. If you want to add GSAP to one, the agency and studio designs in the Portfolio & Agency category are where scroll sequences tend to fit, and the styling docs show where component styles and scripts live. For bundling rules, see the official Astro client-side scripts guide.

FAQ

Can you use GSAP with Astro?

Yes. Install gsap, import it in a <script> tag inside any .astro component, register the plugins you use, and write your animations. Astro bundles the script as a module; no integration or UI framework is needed.

Is GSAP free to use on commercial Astro sites?

Since 2025, GSAP and all of its plugins, including ScrollTrigger, SplitText and MorphSVG, are free to use, including on commercial projects. Check the license on gsap.com for the current terms before you ship.

Why do my GSAP animations stop working after navigation in Astro?

With <ClientRouter />, bundled scripts run only on the first page. Move setup into an astro:page-load listener and revert old animations in astro:before-swap so each new page gets fresh tweens and ScrollTriggers.

Should I use GSAP or CSS animations in Astro?

Use CSS for hover states, simple entrances and loaders, since it needs no JavaScript. Use GSAP when you need sequenced timelines, pinning, scroll scrubbing, text splitting or SVG path animation.

Does GSAP hurt Astro performance?

GSAP adds a modest amount of JavaScript to the pages that import it and none to pages that don’t. Animate transforms and opacity, avoid animating the LCP element on load, and load plugins only where they’re used.