npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@webflow/pjax-max

v5.0.0

Published

Lightweight PJAX library for page transitions

Readme

pjax-max

A lightweight (~5.5KB gzipped), zero-dependency PJAX library for page transitions. Navigate between pages without full reloads, with full control over transition animations.

Built on top of the browser's native History API, Fetch API, and EventTarget.


Hand it to an agent

Everything an AI coding agent needs to use pjax-max well ships in the package:

  • The guide, node_modules/@webflow/pjax-max/skills/pjax-max/: how to set a page up, how to turn a description or a reference site into one of the proven transition recipes, and how to verify the result in a browser. It is an Agent Skill, so it can also be installed for your agent with npx skills add webflow/pjax-max.
  • The types, dist/pjax-max.d.ts: the whole core API in one file. @webflow/pjax-max/debug and @webflow/pjax-max/head have their own.
  • The diagnostics, @webflow/pjax-max/debug: the mistakes that otherwise fail silently, said in the console, each with the section of the guide that fixes it.
  • The check, skills/pjax-max/scripts/check.mjs: the guide's definition of done, run against your dev server in a real browser in about a minute.

A prompt to start from:

Add page transitions to this site with pjax-max. If it isn't installed, install @webflow/pjax-max and gsap. Then read node_modules/@webflow/pjax-max/skills/pjax-max/SKILL.md and follow it: set the pages up as it describes, and use its Mask recipe as the default transition, with an entrance on every page. Before you call it done, verify it in a browser against the skill's checklist and tell me what you checked.

There are more in skills/pjax-max/assets/prompts.json: one for each recipe, one for matching a reference, one for fixing a transition.

To have your agent read the guide whenever it touches a transition, add this to the project's AGENTS.md or CLAUDE.md. It ships as skills/pjax-max/assets/agents-snippet.md, and its comments mark where it starts and ends, so a newer one can replace it in place:

<!-- BEGIN:pjax-max-agent-rules -->
## Page transitions

This site's page transitions are pjax-max. Before writing or changing one,
read `node_modules/@webflow/pjax-max/skills/pjax-max/SKILL.md` and follow it: start
from its recipes, hold any new motion to its house rules
(`references/taste.md`), and verify in a browser with its check script
(`scripts/check.mjs`) before calling the work done. Before changing a
transition copied from a recipe, diff it against the shipped one in
`recipes/`. Code written from memory of Highway.js or Barba runs and
quietly does the wrong thing.
<!-- END:pjax-max-agent-rules -->

Install

npm install @webflow/pjax-max
import { Core, Renderer, Transition } from '@webflow/pjax-max';

Or via CDN:

<script src="https://unpkg.com/@webflow/pjax-max"></script>
<script>
  const { Core, Renderer, Transition } = PjaxMax;
</script>

HTML Setup

pjax-max requires two data attributes in your markup:

<body>
  <nav>
    <a href="/">Home</a>
    <a href="/about">About</a>
  </nav>

  <main data-router-wrapper>
    <article data-router-view="home">
      <!-- page content -->
    </article>
  </main>
</body>
  • data-router-wrapper — The container that holds views. Stays in the DOM across navigations.
  • data-router-view="slug" — The swappable view element. The slug maps to your renderers.
  • data-router-data='{…}' — Optional, on the view: what transitions should know about the page, as JSON. See View Data.

Quick Start

import { Core, Transition } from '@webflow/pjax-max';
import { gsap } from 'gsap';

const mask = document.querySelector('.mask'); // fixed, full screen, under the header

// 1. Define a transition: cover the page in the next page's color, swap the
//    views beneath it, and switch the cover off
class Mask extends Transition {
  async out({ next }) {
    const { data } = await next; // the next page, as soon as it's in hand

    mask.style.backgroundColor = data.backgroundColor;
    // Awaited, so the half resolves with nothing rather than with the tween
    await gsap.to(mask, { autoAlpha: 1, duration: 0.18, ease: 'sine.out' });
  }

  in({ from, data }) {
    from.remove();
    document.documentElement.style.backgroundColor = data.to.backgroundColor;
    // Returned, as every half has to finish: by a Promise or tween, or by done()
    return gsap.set(mask, { autoAlpha: 0 });
  }
}

// 2. Initialize
const core = new Core({
  transitions: {
    default: Mask
  }
});
<article data-router-view="home" data-router-data='{"backgroundColor": "#146ef5"}'>

That's it. Every same-origin link — including ones added to the page later — now navigates with your transition. With no transitions at all, new Core() still works: views swap instantly. Best Practices explains why this transition is a mask rather than a fade, and what the page needs for the cover to go without a flash.

This Mask, Slide and Instant are in the package complete, as the docs site runs them, with the page setup they share: skills/pjax-max/recipes. The examples in this README are excerpts of those files.

Core

Constructor Options

const core = new Core({
  renderers: { ... },    // Map of slug -> Renderer class
  transitions: { ... },  // 'default', view-slug, pathname and contextual keys, plus optional _popstate
  choose: ({ from, to, direction }) => { ... }, // A key of transitions, picked from both pages (see Choosing by Both Pages)
  onLeave: [ ... ],      // Functions called at the start of every out transition
  onEnter: [ ... ],      // Functions called at the start of every in transition
  pageEntrance: { ... }, // Functions called after the in transition completes, keyed by namespace
  head,                  // Merge marked <head> and <body> elements across pages, from '@webflow/pjax-max/head' (see Head & Body Merging)
  runViewScripts: false, // Execute <script> tags inside the incoming view (default false)
  manualScrollRestoration: false, // Scroll to top after each navigation (default false)
  cleanAnchors: false,   // Drop a URL's #anchor from the address bar once the page is at it (default false; see Anchors in the address bar)
  cache: { size: 10, ttl: 300000 }, // Pages the cache holds, and ms an unvisited prefetch stays fresh (see Cache size)
  prefetch: { concurrency: 2 },     // Hover prefetches that run at once; a new one aborts the oldest
  debug,                 // Development diagnostics, from '@webflow/pjax-max/debug' (see Debugging)
});

Properties

| Property | Type | Description | |---|---|---| | core.transitioning | boolean | true while a navigation is in progress. After a fallback it stays true until the browser replaces the page, or the navigation has been undone | | core.namespace | string | The current view's data-router-view slug | | core.location | object | The current location — { href, origin, pathname, anchor }. For the query, new URL(core.location.href).searchParams | | core.cache | Map | Page cache, keyed by absolute URL without the #fragment. It holds the pages used last, and pjax-max never replaces a page in it: see Precaching and Cache size | | core.state | object | The history entry's own state, kept there with setState(); {} on an entry with none. See Entry State |

Everything else on the instance is private.

Methods

| Method | Description | |---|---| | core.redirect(url, contextual?, trigger?) | Navigate programmatically. Relative URLs resolve against the current page. Returns a Promise that resolves when the navigation ends | | core.prefetch(links, { intent }?) | Prefetch URLs or link elements into the cache. intent counts them as hover prefetches | | core.precache(url, html) | Seed the cache with HTML you already have, without fetching | | core.setState(values) | Merge values into the history entry's state, which the browser keeps with the entry. Returns false, keeping nothing, if the browser has moved to another entry. See Entry State | | core.destroy() | Remove every listener, the event mask and the announcer; links load normally afterwards |

Links don't need attaching. One delegated listener on the document handles every link, including those inserted after load and those inside open shadow roots. To hand a link back to the browser, give it or an ancestor data-router-disabled.

Events

Listen to navigation lifecycle events using the native addEventListener API:

core.addEventListener('NAVIGATE_OUT', (e) => {
  const { from, trigger, location } = e.detail;
});

core.addEventListener('NAVIGATE_IN', (e) => {
  const { to, trigger, location } = e.detail;
});

core.addEventListener('NAVIGATE_END', (e) => {
  const { from, to, trigger, location } = e.detail;
});

from and to are { page, view, data }: page is the parsed Document of that page, view is the live [data-router-view] element (the outgoing one may already be detached by the time NAVIGATE_END fires), and data is the view's data. trigger is the clicked link, 'popstate' for back/forward, or 'script' for redirect().

By NAVIGATE_IN, document.title is the incoming page's, so a page view sent from it, or from onEnter, reports the page the visitor is going to.

Navigation Lifecycle Hooks

The onLeave and onEnter arrays let you run functions on every navigation without repeating logic in each transition. Common uses: closing menus, destroying scroll instances, resetting UI state. They run whichever transition plays, the instant swap included, so teardown belongs here or in a Renderer, not in a transition: when no transition matches, none of yours runs.

const core = new Core({
  transitions: { default: Mask },
  onLeave: [
    () => scroll?.destroy(),
    () => megaNav.isOpen && megaNav.close(),
    () => mobileMenu.isOpen && mobileMenu.close(),
  ],
  onEnter: [
    ({ to, location }) => console.log('Entering:', location.pathname, to.view),
  ],
});

onLeave runs before the out transition. onEnter runs after the new view is in the DOM but before the in transition plays. Each function receives the same detail as the matching event — NAVIGATE_OUT for onLeave, NAVIGATE_IN for onEnter. core.namespace and document.title are updated before onEnter fires, so both reflect the incoming page.

Page Entrance

The pageEntrance option lets you run functions after the in transition completes, keyed by namespace. This is where each page's entrance plays — its elements animating in, from where onEnter hid them. A default key acts as a fallback for any namespace without a specific entry.

// Hidden in one set: GSAP reads every element before writing any
const hide = view => gsap.set(view.querySelectorAll('[data-entrance]'), { autoAlpha: 0, y: 24 });

const core = new Core({
  transitions: { default: Mask },
  onEnter: [({ to }) => hide(to.view)],
  pageEntrance: {
    default: ({ view }) => {
      gsap.to(view.querySelectorAll('[data-entrance]'), { autoAlpha: 1, y: 0, stagger: 0.06 });
    },
    home: ({ view }) => {
      gsap.to(view.querySelector('.hero'), { autoAlpha: 1, y: 0, duration: 0.6 });
    },
  }
});

// onEnter runs on navigation; the first page is hidden by hand
hide(document.querySelector('[data-router-view]'));

Each function receives { view, from, trigger, location, data, transition }:

| Property | Description | |---|---| | view | The incoming view element (data-router-view), live in the document | | from | The previous view element (usually detached by now), or null on initial page load | | trigger | The link element that triggered navigation, 'popstate', 'script', or null on initial load | | location | The current location object | | data | The incoming view's data | | transition | The transition instance whose in brought the view in, or null on initial load. Its animation may still be playing, if in called done() early |

Page entrance also fires on the initial page load (after the initial renderer sets up), so your entrance animations run on first visit too. For the first page to enter without a flash, hide what enters in critical CSS as well — see Best Practices.

An entrance can follow the transition that brought its page in: its class, its name, or anything its halves left on this. Slide knows which side its view came from, so a split headline can come in from that side, the glyph nearest it first:

pageEntrance: {
  default: ({ view, transition }) => {
    // -1 after a Slide from the left (back), 1 after anything else
    const d = transition?.direction === -1 ? -1 : 1;

    gsap.fromTo(view.querySelectorAll('.char'), { x: 120 * d }, {
      x: 0,
      stagger: { each: 0.026, from: d < 0 ? 'end' : 'start' }
    });
  }
}

The recipes' entrance (entrance.js) does this a line at a time, for any headline marked data-split, and from the left mirrors the rest of the glyphs' start too: they turn the same way, about a point on the other side of each glyph.

Renderers

Renderers control page-specific setup and teardown. Extend the base Renderer class and override lifecycle hooks. Inside a hook, this.view is the live view element and this.properties holds the parsed page ({ url, page, view, slug, data }, where data is the view's data):

class HomeRenderer extends Renderer {
  onEnter() {
    // Called when the view is added to the DOM
    this.slider = new Slider(this.view.querySelector('.slider'));
  }
  onEnterCompleted() {
    // Called after the in transition completes
  }
  onLeave() {
    // Called before the out transition starts
  }
  onLeaveCompleted() {
    // Called after the out transition completes
  }
}

Map renderers to view slugs:

const core = new Core({
  renderers: {
    home: HomeRenderer,
    about: AboutRenderer,
  },
  transitions: { default: Mask }
});

Renderers support dynamic imports for code splitting:

const core = new Core({
  renderers: {
    home: () => import('./renderers/home.js'),
  }
});

Transitions

Transitions control the animation between views. Extend the base Transition class and implement out and in. Each half finishes when it calls done() or when the Promise it returns settles:

class Mask extends Transition {
  out({ next, done }) {
    // Wait for the next page, then cover this one in its color, and call done()
    next.then(({ data }) => {
      mask.style.backgroundColor = data.backgroundColor;
      gsap.to(mask, { autoAlpha: 1, duration: 0.18, ease: 'sine.out', onComplete: done });
    });
  }

  in({ from, to, data, trigger }) {
    from.remove();
    document.documentElement.style.backgroundColor = data.to.backgroundColor;
    // Or return a Promise: GSAP tweens and timelines are thenable
    return gsap.timeline().set(mask, { autoAlpha: 0 });
  }
}

Each half gets:

| Property | Description | |---|---| | from | The outgoing view element, live in the document | | to | The incoming view element, live in the document — in only | | data | { from, to }, each view's data. to is only known in in | | next | out only: a Promise for the incoming page, { url, slug, view, data, page }, parsed but not yet in the document. It resolves as soon as the page is in hand — at once from the cache or a finished prefetch. If the page can't be loaded it stays pending while the browser loads it instead, and resolves with the page that was left if that one comes back | | trigger | The clicked link, 'popstate', or 'script' | | direction | 'back' or 'forward' when the visitor went back or forward, null for a link or redirect(). It doesn't depend on which key picked the transition; this.name is that key | | done | Call to finish the half, instead of returning a Promise |

A half you leave out finishes immediately, and the default in removes the outgoing view — so a bare Transition is an instant swap. A half that neither calls done() nor returns a Promise never finishes, and the navigation waits on it.

A fresh transition instance is created for every navigation. When one transition drives both halves — a contextual, choose, pathname or popstate match, or the same view-level transition on both sides — out and in run on the same instance, so out can hand state to in through this:

// Nothing animates when the page is already in hand; otherwise it's Mask
class Instant extends Mask {
  async out(context) {
    // A cached or prefetched page resolves within this task; one still loading can't
    this.instant = await Promise.race([
      context.next.then(() => true),
      new Promise(resolve => setTimeout(() => resolve(false)))
    ]);

    if (!this.instant) return super.out(context);
  }

  async in(context) {
    if (!this.instant) return super.in(context);

    context.from.remove(); // swap, and let the page's entrance play
  }
}

The page's entrance gets the instance that played in, as transition, so a transition can hand state on to it the same way.

Default vs. Pathname vs. Contextual Transitions

A default transition applies to all navigations. Pathname-based transitions let you assign transitions to specific destination pages by matching on the URL pathname:

const core = new Core({
  transitions: {
    default: Mask,
    '_home': Instant,              // used when navigating to /
    'about': Slide,                // used when navigating to /about
    'work/project': Slide,         // used when navigating to /work/project
    slide: Slide,                  // available as a contextual override
  }
});

The pathname is cleaned of leading/trailing slashes before lookup (e.g., /about/ → about). The root path / maps to _home. The match is exact — /work/project-name will not fall back to work.

Keys starting with _ are reserved for the library (_home, _popstate).

Use contextual transitions on specific links with the data-transition attribute to override both pathname-based and default transitions:

<a href="/gallery" data-transition="slide">Gallery</a>

When this link is clicked, Slide is used regardless of what pathname-based or default transition would apply.

Priority (highest to lowest):

  1. data-transition attribute on the link (click navigation only), or redirect()'s contextual
  2. The key choose returns
  3. Pathname-based match in the transitions map
  4. _popstate direction transition (back/forward only)
  5. View-slug match in the transitions map: the outgoing view's for the out half, the incoming view's for the in half
  6. default transition

With _popstate.priority: true, items 3 and 4 swap — popstate transitions win over pathname matches. choose stays above both.

Tiers 1–4 are known before the next page is fetched, so the winner drives both the out and the in half. Otherwise each half resolves on its own: the out half from the outgoing view's slug and the in half from the incoming one, each falling back to default. If nothing matches at all, the view swaps instantly.

Pathname keys and view-slug keys share one flat map, so a key like about matches both the page at /about and any view with data-router-view="about". When both could apply, the pathname wins. Keys beginning with _ are reserved and never match a view slug.

Popstate Transitions (Back/Forward)

By default, browser back/forward navigations use the default transition. The _popstate reserved keyword lets you specify different transitions for each direction:

const core = new Core({
  transitions: {
    default: Mask,
    _popstate: {
      back: Slide,
      forward: Slide,
    }
  }
});

Both back and forward are optional — specify one, both, or neither. If a direction is not specified, the default transition is used. If neither is specified, _popstate is ignored entirely. One class can serve both: each half gets direction, 'back' or 'forward', which is how Slide knows which side to come from, whatever key picked it.

pjax-max tracks history position internally to detect whether a popstate event is a back or forward navigation, since the browser does not expose this.

Popstate Priority

By default, pathname-based transitions take precedence over popstate transitions. If you have both about: Instant and _popstate.back: Slide, pressing back to /about will use Instant.

Set priority: true to make popstate transitions win over pathname matches:

const core = new Core({
  transitions: {
    default: Mask,
    about: Instant,
    _popstate: {
      back: Slide,
      forward: Slide,
      priority: true,  // popstate transitions win over pathname-assigned transitions
    }
  }
});

With priority: true, pressing back to /about uses Slide instead of Instant. Defaults to false.

Choosing by Both Pages

Each key in the map answers one question: which link, which destination, which way through history, which kind of page. Some transitions depend on two or three at once: back from a case study to the home page, where the image goes back into its card, or back and forth between two docs pages, where the sidebar stays still. No order of keys says "and". The choose option does: a function, asked before the rest of the lookup, that returns a key of transitions, or nothing for the usual lookup:

const DOCS = new Set(['docs', 'examples']);

const core = new Core({
  transitions: {
    default: Mask,
    persist: Persist,
    unfold: Unfold,
    _popstate: { back: Slide, forward: Slide, priority: true },
  },
  choose: ({ from, to, direction }) => {
    // Back and forth between docs pages: the sidebar stays where it is
    if (direction && DOCS.has(from.slug) && DOCS.has(to.slug)) return 'persist';
    // Back from a case study to the home page: the image goes back into its card
    if (direction === 'back' && from.slug === 'work' && to.slug === 'home') return 'unfold';
  }
});

Everywhere else, back and forward slide, as _popstate says. choose gets:

| Property | Description | |---|---| | from | The page being left: { slug, location }, its view's data-router-view value and where it is | | to | Where the navigation goes: { slug, location }. On back and forward, slug is the view pjax-max showed at that history entry, kept in the entry's state, so it survives a reload. On a link or redirect() it's null: the out half starts before the next page is fetched, so its view isn't known yet. Use to.location there, or the link itself, trigger | | direction | 'back' or 'forward' on back and forward, null for a link or redirect() | | trigger | The clicked link, 'popstate', or 'script' |

  • A link's data-transition comes first: when it names a transition, choose isn't asked. A click and a back press never happen together, so the two are never weighed against each other.
  • The key it returns drives both halves on one instance, named by that key, as a data-transition name does. Return the key itself, as a string, at once: not the class, and not a promise. A key that names no transition leaves the usual lookup, and the diagnostics say so.
  • It runs after onLeave, so a map that onLeave emptied for reduced motion still swaps instantly, whatever choose returns.
  • If it throws, the page loads normally, as for any other error in a navigation.
  • It isn't asked again for a page that comes back when the browser doesn't load the one it was sent to: the transition whose out ran plays its in.

Overlapping Transitions

The old view stays in the DOM until you explicitly remove it. This means you can run both views simultaneously for overlapping transitions:

class Slide extends Transition {
  // 1 from the right, -1 from the left. The page's entrance reads it too
  direction = 1;

  async out({ from, data }) {
    // Fixed where it is, so the new view can lay out beneath it
    const { top } = from.getBoundingClientRect();

    gsap.set(from, { position: 'fixed', top, left: 0, right: 0, zIndex: 0 });
    from.style.backgroundColor = data.from.backgroundColor;
    // Don't call from.remove() here — let the in transition overlap
  }

  async in({ from, to, data, direction }) {
    // Back comes from the other side, whatever key picked Slide
    this.direction = direction === 'back' ? -1 : 1;

    const d = this.direction;

    to.style.backgroundColor = data.to.backgroundColor;
    gsap.set(to, { position: 'relative', zIndex: 1 });

    await gsap.timeline({ defaults: { ease: 'expo.out' } })
      .fromTo(to, { xPercent: 100 * d }, { xPercent: 0, duration: 0.85 }, 0)
      .to(from, { xPercent: -45 * d, duration: 0.95 }, 0);

    from.remove(); // Remove the old view when the new one covers it

    // Hand its styles back by removing them: all but a will-change, which stays
    for (const prop of ['position', 'z-index', 'transform', 'translate', 'rotate', 'scale', 'background-color']) to.style.removeProperty(prop);
  }
}

The out above is async and so returns a Promise; a plain method that neither returns one nor calls done() would never finish. While two views share the screen, each needs its own page's color — a view without a background shows the one behind it. Take them from the views' data, not from the page's styles.

The complete Slide (skills/pjax-max/recipes/slide.js) also cuts each view to the screen first, so only what's on screen moves, not the whole page (pin() and screenful() in layers.js); veils the old view as the new one comes over it; brings the new page's color in behind a see-through header; and calls done() 22% of the way through in (16% going back), so the page's entrance plays over the rest of the slide.

View Data

Give a view data-router-data to tell transitions about its page: its color, its name, anything JSON can hold.

<article data-router-view="work" data-router-data='{"backgroundColor": "#146ef5"}'>

It's parsed once, when the page is — from a prefetch or the cache — so it's in hand before the view is in the document, and it reaches everything that sees the view:

  • transitions: data.from and data.to, and in out, (await next).data
  • events, onLeave and onEnter: from.data and to.data
  • pageEntrance: data
  • renderers: this.properties.data

A view without the attribute has {}. Anything that isn't a JSON object is ignored, with a warning.

A color can be any CSS color, var() included, which keeps a palette in CSS. Set it as a style; to tween it, read it back resolved from getComputedStyle() and give the tween both ends — GSAP reads an element's inline value before its computed one, and would take var(--brand-pink) for CSS's own pink.

Read what a transition needs from here rather than from the page. A transition that finds the next page's name in a link's text, or measures its color from a stylesheet, depends on markup it doesn't own, and can't know either before the view is in the document.

Entry State

A page can keep state on its history entry: which tab is open, how a product is shown, a filter. The browser keeps it with the entry, so back, forward and a reload bring the page back with it, and a link starts a new entry without it.

class Product extends Renderer {
  onEnter() {
    // A new entry has no tab: the first one. Back, forward or a reload: the tab that was open.
    showTab(this.view, core.state.tab ?? 'details');

    this.view.addEventListener('click', e => {
      const tab = e.target.closest('[data-tab]')?.dataset.tab;

      if (tab) {
        showTab(this.view, tab);
        core.setState({ tab });
      }
    });
  }
}

const core = new Core({ renderers: { product: Product } });
  • core.state is the entry the router is at, and during a navigation the one it's going to, from NAVIGATE_OUT on: it's there for choose(), the transition, onEnter and the renderer's hooks. So keep what a page needs as it changes, not in onLeave, where the entry is already the next one.
  • setState() merges, and writes the entry only when a value changes. Values are copied the way history.state copies them: strings, numbers, booleans, arrays and plain objects, not functions or elements.
  • A new entry starts with none: a link's, redirect()'s, and the one the browser adds for an in-page anchor. The state stays through the changes pjax-max makes to an entry: the view it notes there, an anchor cleanAnchors takes off the address, a reload.
  • It's read and written only on the router's entry. After a back press during a navigation the browser is already on another entry, so the page that lands reads {} and setState() returns false; the entry the browser went back to keeps its state for its own page, which comes in next.
  • It lives at history.state.pjaxMax.state. A script that replaces history.state outright drops it, with the rest of pjax-max's own.

Best Practices

pjax-max leaves the animation to you. These are the rules the pjax-max docs site follows, with the reasons that are easy to miss.

Animate a mask, not the view. A view is the whole page, most of it off screen: fading it composites all of it, and the next one has to come in the same way. Cover the page instead, with a fixed layer the size of the screen, over the content and under the header, in the next page's color. Swap the views beneath it, and then switch it off rather than fading it — gsap.set(mask, { autoAlpha: 0 }). Don't give a fixed header a background of its own, which would keep the old page's color over the mask: paint the page's color behind it in a layer under the mask, which the mask covers too, and the header stays put while the page changes under it.

Give the page its color from data. Views have no background of their own; the page's color is the root's, set from the incoming view's backgroundColor as the views swap, while the mask covers them (and rendered by the server for the first page). Themes can still color the type. A transition that shows two views at once gives each its own page's color for as long as they share the screen.

Give every page an entrance. Switching the mask off shows nothing new only if everything beneath it is waiting to enter. So hide what enters in critical CSS, before any script runs — behind a class a script adds, and takes off after a few seconds in case the main script never arrives, and only when motion is welcome:

<script>
  document.documentElement.classList.add('js-loading');
  setTimeout(() => document.documentElement.classList.remove('js-loading'), 3000);
</script>
<style>
  @media (prefers-reduced-motion: no-preference) {
    .js-loading [data-entrance] { visibility: hidden; }
  }
</style>

Then take them over from script before lifting the class — one gsap.set() over every element, in onEnter for each new view and by hand for the first — and play them in pageEntrance: everything on the first screen at once, in order, and the rest as it scrolls into view. Hidden with visibility, nothing waiting to enter can be focused or clicked; once the page has entered, make what's still waiting below the fold visible again, but transparent, so it stays in the tab order. If the timeout lifted the class before your script ran, the page has been seen: show it as it is, rather than hiding it to play its entrance.

Prefetch. A mask that takes its color from the next page waits for that page. With data-prefetch="hover", it's in hand by the click.

Scroll Restoration

By default, pjax-max lets the browser handle scroll position naturally. If you want to always start at the top of the page after navigation, enable manualScrollRestoration:

const core = new Core({
  transitions: { default: Mask },
  manualScrollRestoration: true
});

When enabled, this sets history.scrollRestoration = 'manual' and takes over scrolling, right after the new view is added and before the in transition plays:

  • Link and redirect() navigations start at the URL's #anchor if the new page has one, otherwise at the top. Use CSS scroll-margin-top to clear a fixed header.
  • Back and forward return to where that page was scrolled when you left it.
  • A reload starts at the top: the browser no longer restores the position, and the positions pjax-max keeps don't outlive the page.

Defaults to false.

Anchors in the address bar

A link to /about#team leaves #team in the address bar. To drop it once the page is there, set cleanAnchors:

const core = new Core({
  transitions: { default: Mask },
  manualScrollRestoration: true,
  cleanAnchors: true
});

A navigation to a URL with an #anchor then puts the new view in place (with manualScrollRestoration, at the anchor) and, in the same task, before NAVIGATE_IN, takes the anchor off the address. It isn't lost:

  • The history entry keeps it. Back and forward return to the URL with the anchor, and take it off again once the view is in place. After a reload, when pjax-max no longer has the page's scroll position, they start it at the anchor.
  • The events and core.location keep it, as location.anchor. Read it there, not from window.location.hash.
  • A link to an anchor on the page on screen is still the browser's. It jumps, and the anchor stays in the address bar, which is how a heading's own link gives a reader a URL to copy. To glide there instead and leave the address as it is, preventDefault() the click and scroll from your own code.
  • A page loaded with an anchor (a new tab, a pasted link) keeps it: the browser scrolls to it as the page loads. A reload loads the address as the bar shows it, so a page whose anchor was taken off reloads at its top.

Defaults to false.

Event Mask

During transitions, user interactions like scrolling, clicking, or swiping can cause visual glitches. pjax-max automatically creates an invisible full-screen overlay that blocks these gestures while a transition is in progress.

The mask is a [data-pjax-mask] element appended to the <body> on initialization with pointer-events: none. When a navigation starts it switches to pointer-events: auto, swallowing clicks and preventing wheel and touchmove. When the transition completes it switches back to none. After a fallback to a normal page load it stays on, since the page is about to be replaced.

Back/forward presses made while a transition is running are queued and played once it finishes, rather than interrupting it.

No setup required — this is fully automatic.

Accessibility

A navigation tells assistive technology what a page load would:

  • The new page is announced. As each new view goes in, before NAVIGATE_IN, a visually hidden live region that pjax-max appends to the <body>, [data-pjax-announcer], reads out the incoming page's <title>. Give every page a title of its own.
  • Focus starts over. Once the in transition has finished, focus left in the outgoing view, or nowhere, moves to the start of the document, where a page load leaves it: nothing is focused, no focus ring shows, and the next Tab reaches the page's first focusable element, its skip link if it has one. Focus anywhere else stays where it is: outside the wrapper (the header link that was pressed, a search field that calls redirect() as you type), or in the new view.

So to focus something else, put focus in the new view: the new page's heading from onEnter or a Renderer, or, from in, the same link in a sidebar the transition keeps across pages. pageEntrance runs after the reset, so it can focus anything. An element hidden with visibility, as entrances hide theirs, takes focus only once it's shown. A site that announces pages itself can remove [data-pjax-announcer].

Prefetching

pjax-max can prefetch pages and store them in the cache for instant navigation.

Critical Prefetch

Fetched as soon as the browser is idle after load (and after each navigation). Use for primary navigation links:

<a href="/about" data-prefetch="critical">About</a>

These go out at priority: 'low', so they never take the connection from what the page on screen is still loading. A hover prefetch, an intent one and a navigation ask at the browser's default.

Hover Prefetch

Fetched on hover, and on keyboard focus. Handled by one delegated listener, so it works for links added later too:

<a href="/blog" data-prefetch="hover">Blog</a>

A pointer that crosses a menu hovers every link on its way, so at most two hover prefetches run at once (the prefetch.concurrency option): a new one aborts the oldest, unless a click is already waiting on it.

Programmatic Prefetch

For links inside menus or components that open dynamically:

// When a mega nav opens, prefetch its links
function openMegaNav() {
  megaNav.open();
  const links = megaNav.querySelectorAll('a');
  core.prefetch(links);
}

core.prefetch() accepts a link element or URL string, or any iterable of them. Relative URLs are resolved against the current page. It skips URLs already in the cache and deduplicates in-flight requests — a click on a link that's still prefetching waits for that request instead of starting a second one. Your own intent signals, a hover with a delay say, can share hover prefetch's limit: core.prefetch(link, { intent: true }). Without intent, they go out at priority: 'low', as critical prefetches do.

Precaching

When you already have a page's HTML — from a service worker, a build-time manifest, a CMS payload, the response to a form you posted with fetch() — core.precache() puts it straight into the cache without a network request:

core.precache('/about', htmlString);

Returns true when the cache was populated, and false if the arguments aren't strings, the URL is cross-origin or already cached, or the HTML has no [data-router-view]. Relative URLs are resolved against the current page, so the key always matches what navigation will look up.

pjax-max never replaces a page in the cache, and a precached page is never evicted (see Cache size), so precache() wins over a fetch of the same URL that's still in flight: the precached page stays when the fetch lands, and it's the one a navigation waiting on that fetch shows. To refresh a page that's already cached, delete its entry first. The keys are absolute URLs without the #fragment:

const url = new URL('/cart', location.href).href;

core.cache.delete(url);
core.precache(url, htmlString);

Cache size

The cache holds the 10 pages used last (cache.size): a page used least recently goes first, and is fetched again the next time it's needed. The page on screen stays, and so does a precached page, which pjax-max may have no way to fetch again (a page you precached from a POST, say). A page that sits under two URLs, the one asked for and the one a redirect ended on, counts once and goes with both.

A prefetched page nobody has visited goes stale after five minutes (cache.ttl): a navigation to it then fetches it again. A page that has been on screen doesn't expire.

const core = new Core({ cache: { size: 30, ttl: 60_000 } });

{ size: Infinity, ttl: Infinity } keeps everything, until the page is closed.

Head & Body Merging

By default only the view inside data-router-wrapper changes between pages. Everything else — meta tags, stylesheets, analytics snippets, a header that differs per page — stays as it was on first load. The merge in @webflow/pjax-max/head reconciles those regions, handed to Core as its head option:

import { Core } from '@webflow/pjax-max';
import { head } from '@webflow/pjax-max/head';

const core = new Core({
  transitions: { default: Mask },
  head
});

It is a separate module (about 0.9KB gzipped), so a site that doesn't merge doesn't load it. head: true is ignored, and the diagnostics say so. With the <script> build, load dist/head.global.js and pass PjaxMaxHead.head.

Mark the elements you want kept in sync with data-pjax-head, giving each a stable key:

<head>
  <meta name="description" content="..." data-pjax-head="description">
  <link rel="canonical" href="https://example.com/about" data-pjax-head="canonical">
</head>

On each navigation, keys present in both pages with identical markup are left alone, keys whose content changed are replaced in place, keys only in the old page are removed, and keys only in the new page are appended.

For groups of arbitrary nodes that have no single wrapping element, use zone markers — a matched pair of HTML comments. Everything between them is replaced as one block:

<!-- pjax-zone:promo -->
<div class="banner">Spring sale</div>
<p>Ends Friday</p>
<!-- /pjax-zone:promo -->

Zones work in both <head> and <body>. Anything inside data-router-wrapper is excluded from body reconciliation, since that's the view's job.

Scripts the merge adds or replaces run once the new view is in, in the order a load of the page runs them: in document order, head first. An external script holds back the scripts after it until it has loaded or failed, defer and module scripts run after the rest, and async ones run whenever they load. So a library and the code that uses it can sit together before </body>:

<!-- pjax-zone:slider -->
<script src="https://cdn.example.com/slider.js"></script>
<script>new Slider('.slider');</script>
<!-- /pjax-zone:slider -->

A script whose markup is the same on both pages doesn't run again. A zone is replaced as one block, though, so a change anywhere in it runs every script in it again, a library included: give a library that every page loads a zone or a key of its own, and the code that differs between pages another.

createHead() makes the merge with settings of your own:

import { createHead } from '@webflow/pjax-max/head';

const core = new Core({
  head: createHead({
    attribute: 'data-pjax-head', // key attribute to match on
    rerunScripts: true           // re-execute <script> elements that are added or replaced
  })
});

View Scripts

<script> tags inside a view do not run when the view is swapped in. This is a browser rule, not a pjax-max choice: markup inserted with insertAdjacentHTML has its scripts marked "already started" and they are never executed.

Set runViewScripts to re-create them so they run:

const core = new Core({
  transitions: { default: Mask },
  runViewScripts: true
});

Scripts execute after the view is in the DOM and before the in transition plays, in the order a load of the page runs them: an external script holds back the scripts after it until it has loaded or failed, defer and module scripts run after the rest, and async ones run whenever they load. With the head merge, they take their place among the scripts it adds, after the head's and before the ones after the view, so a view's script can use a library from a head zone.

It is off by default because most sites are better served by initialising from onEnter or a Renderer hook — a script that runs on every visit to a page will also run again on every return to it, which is rarely what inline page scripts expect.

Disabling PJAX on Links

Add data-router-disabled to a link, or to any ancestor to opt out a whole region. It is read at click time, so it can be added or removed whenever:

<a href="/legacy" data-router-disabled>Normal navigation</a>

<div data-router-disabled>
  <a href="/admin">Also normal</a>
</div>

The browser also keeps:

  • other origins, and non-HTTP schemes like mailto: and tel:
  • links with a target other than _self, and links with download
  • links to a file, going by the extension the path ends in: 7z, aac, apk, avi, avif, bmp, bz2, css, csv, dmg, doc, docx, epub, exe, gif, gz, ico, ics, iso, jpeg, jpg, js, json, m4a, m4v, md, mjs, mkv, mov, mp3, mp4, msi, ogg, pdf, pkg, png, ppt, pptx, rar, rtf, svg, tar, tgz, tif, tiff, ts, txt, vcf, wav, webm, webp, xls, xlsx, xml, zip
  • modified or non-primary clicks — Cmd/Ctrl, Shift, Alt, middle-click
  • in-page #anchor links on the current page
  • clicks that another handler already called preventDefault() on

The file list is a list on purpose. A page whose URL merely has a dot in it, like /docs/v2.1 or /team/jo.smith, is still routed. A site's own scripts, styles, data and Markdown are on it, because a link to one (a page's Markdown copy, a type declaration) wants the file, and routing it would only play out before the page load that has to follow. So a page whose path ends in one of those, like /blog/moving-to-next.js, loads in full; with a trailing slash, /blog/moving-to-next.js/, it's routed. For a file it doesn't cover, or a download URL with no extension, add download or data-router-disabled to the link.

Falling Back to a Normal Page Load

When a navigation can't be done in place, pjax-max hands the URL to the browser instead of leaving the page half-transitioned. That happens for an error status, a response that isn't HTML (JSON, a file whose URL has no extension), a page without [data-router-view], and network or transition errors — the latter are also logged to the console.

A transition error is anything a half throws, or a rejection of the Promise it returns. That includes element.animate().finished, which rejects when its animation is cancelled: cancel an animation that a half returned and the navigation ends in a page load.

The URL is loaded with location.assign(). When it has a #fragment and the address bar already shows that page, as it does once a navigation is under way, the browser would only jump within the current page, so pjax-max calls location.reload() instead. With the browser's own scroll restoration, a reload keeps the scroll position rather than scrolling to the fragment.

After core.destroy() nothing falls back: a navigation that was still running stops where it is if it fails, with no page load and nothing logged.

Server redirects are followed: if /old redirects to /new/, the address bar shows /new/ and relative URLs in the new view resolve against it.

If the page pjax-max starts on has no [data-router-wrapper] or [data-router-view], it logs a warning and stays out of the way.

A fallback that isn't an error logs nothing by itself. The diagnostics say why it happened.

When the browser doesn't load the page either

The browser can start that load and stay where it is: the URL answers 204 No Content, it turns out to be a download, or the visitor cancels a beforeunload prompt. Nothing tells the page this has happened, so pjax-max gives the browser one second. If the page is still there after it, the navigation is undone, and the page that was left comes back:

  • The address bar returns to its URL.
  • A fresh copy of its view comes in through the in half of the transition instance whose out played, once that out has finished. Whatever out covered, pinned or hid is put right by the transition that did it, and an out that is waiting on next gets this page.
  • It runs as a navigation, with the page that came back as its location and the original trigger: onLeave, NAVIGATE_OUT, NAVIGATE_IN, onEnter, the incoming Renderer's hooks, pageEntrance and NAVIGATE_END all fire. The view and Renderer that were left are not left a second time.
  • With manualScrollRestoration, the page is scrolled to where it was.

Until then the navigation is still running: core.transitioning is true, the mask is on, redirect() does nothing, and back and forward presses wait their turn.

Three things follow from how it works:

  • The view is a fresh copy, as after any navigation, so anything a visitor typed into the old one is gone.
  • The failed URL's history entry is reused, not removed, so one Back press afterwards changes nothing on screen. Stepping back through history instead would cancel a page load that was only slow.
  • A real page load that takes longer than the second isn't harmed: the old page comes back in, and is replaced when the new one arrives.

If the undo fails as well (its in throws, or the out it was waiting for did), pjax-max asks the browser for the page that was left, releases the mask, and stops there.

A link to a file never gets this far when the browser keeps it. For a download that list can't recognize, download or data-router-disabled on the link spares the page the round trip. The diagnostics say when a navigation was undone, and for which URL.

Debugging

import { Core } from '@webflow/pjax-max';
import { debug } from '@webflow/pjax-max/debug';

const core = new Core({ transitions, debug });

While you build, the diagnostics say in the console what would otherwise go wrong silently:

  • an option, a transition, a data-transition name or a key choose returned that is ignored, and why
  • a half that hasn't finished after 3 seconds, and whether it returned nothing (a recipe's in() ends with doneAt(), which a copy may have lost) or a promise that hasn't settled
  • why a navigation became a normal page load; the reason survives that load and is said again as the next page starts
  • a page load the browser didn't follow, so that the navigation was undone
  • a previous view that was never removed
  • a second Core on the page

One info line per navigation names the transitions that ran:

pjax-max: /work → /about in 0.2s. out: "slide", in: "slide".

Every warning ends with the section of the guide that covers it (skills/pjax-max/references/verify.md), so it can be pasted to an agent as it stands.

createDebug({ stall: 5000 }) makes the diagnostics with a different patience, in milliseconds. debug is not a boolean: debug: true only logs a reminder to import the module. The module is separate (about 3.9KB gzipped) and loaded only if you import it, so leave it out of production builds. With the <script> build, load dist/debug.global.js and pass PjaxMaxDebug.debug.

Checking a site

With the dev server running, and playwright-core in the project (it drives the Chrome you already have):

node node_modules/@webflow/pjax-max/skills/pjax-max/scripts/check.mjs http://localhost:5173/ --out frames

It follows the page's links by real clicks and says, for each item of the guide's checklist, what it saw: every navigation in place and at rest with one view, nothing left inline, nothing shown before its entrance, back and forward, a second click mid-navigation, an uncached page on a slow connection, a scrolled start, reduced motion, a narrow screen, a clean console. --out saves a strip of frames per link, which is the part to look at yourself: the script can tell that a transition ended cleanly, not that it looks right.

TypeScript

Types ship with the package. TypeScript doesn't infer an overridden method's parameter from the base class, so annotate it. The type argument is the shape of your views' data:

import { Core, Transition, type InContext, type OutContext } from '@webflow/pjax-max';

type Data = { backgroundColor: string };

class Mask extends Transition<Data> {
  async out({ next }: OutContext<Data>) {
    const { data } = await next;
    // data.backgroundColor is a string
  }

  in({ from, data }: InContext<Data>) {
    from.remove();
    // data.from and data.to
  }
}

const core = new Core<Data>({ transitions: { default: Mask } });

core.addEventListener('NAVIGATE_END', e => e.detail.to.data.backgroundColor);

A second type argument is the shape of the entry state: with new Core<Data, { tab: string }>(), core.state.tab is a string | undefined, and setState() takes only a string tab.

Coming from Highway.js or Barba

pjax-max shares its markup and class names with Highway.js, so code written for Highway looks as if it should work. What differs is easy to get wrong from memory:

  • transitions is one flat map. There is no nested contextual object: a data-transition name is a top-level key, beside pathname keys (about, _home for /) and _popstate.
  • A half finishes by done() or by returning a Promise or a GSAP tween.
  • Events are core.addEventListener('NAVIGATE_END', e => e.detail). There is no on().
  • Links need no attach(): one delegated listener handles links added at any time.
  • Views don't carry data-transition-in / data-transition-out. A transition that styles by them sets its own attribute or class in out and in.

From Barba: the container is the view, leave and enter are out and in, once is pageEntrance, a rule's from and to are choose, and nothing removes the old view for you: in calls from.remove().

The full tables are in skills/pjax-max/references/other-routers.md.

Framework Compatibility

pjax-max swaps server-rendered HTML. That makes it a good fit for multi-page sites and a poor fit for single-page apps that already own routing.

Works well: static HTML, Astro (MPA mode), Eleventy, Hugo, Jekyll, and any server-rendered stack — Rails, Django, Laravel, WordPress. Interactivity should come from one of:

  • event listeners delegated to an element outside the wrapper, which survives the swap
  • custom elements, which upgrade automatically whenever they are inserted into the DOM
  • re-initialisation in onEnter, a Renderer hook, or pageEntrance

Astro islands work for exactly this reason — <astro-island> is a custom element, so it re-hydrates on insertion with no help from the router.

Webflow: a site Webflow publishes works too. Its pages start webflow.js once, as they load, so the guide's Webflow recipe (skills/pjax-max/recipes/webflow.js, set up as webflow.md says) starts webflow.js and the page's interactions again for each page that comes in. It's a recipe you copy into the site's code, like the transitions, not part of the package: pjax-max is no bigger for it, and a site that isn't Webflow's never loads it.

The package can be imported during server rendering — nothing touches the DOM until new Core() runs — so it's safe in Astro frontmatter or any SSR build. Create the Core in client-only code. In Vue, don't wrap it in reactive() (use markRaw() if it has to live in reactive state): the instance is an EventTarget, whose methods don't work through a Proxy.

Not supported: frameworks with their own client-side router — React Router, Vue Router, SvelteKit client navigation. Two routers both driving history will fight over the same state. Component trees mounted into a root element are also inert after a swap: createRoot().render() does not re-run just because new markup appeared, so a React subtree inside the view arrives as dead HTML.

If your framework has a client router, use it. pjax-max is for the case where you don't have one and don't want one.

Browser Support

Any browser with ES2022 class fields and private methods — Chrome/Edge 91+, Firefox 90+, Safari 15+. No IE support.

Development

npm install
npm test          # vitest + happy-dom, then the type test
npm run build     # tsup -> dist/
npm run check     # the package's exports and types, as published

examples/recipes runs the recipes as they ship. Contributors, and their agents, start at AGENTS.md.

License

MIT © Webflow, Inc. Written by Josh Kirk.

pjax-max's markup and API follow Highway.js (MIT, © Dogstudio), which Josh Kirk co-authored.

The MIT license covers the code in this repository. It does not grant any rights to the Webflow name, the Webflow logo, or Webflow's fonts, which are trademarks or proprietary assets of Webflow, Inc.