Barba.js
repository·main·Indexed 12 days ago
https://github.com/barbajs/barbaA lightweight library for creating smooth, SPA-like page transitions in websites. It minimizes page load delays and HTTP requests using a hook-based lifecycle system, a plugin architecture, and support for custom markup. Includes core functionality via @barba/core and official plugins such as @barba/css, @barba/prefetch, and @barba/router.
What's inside Barba.js
- Barba.js (or Barba) is a lightweight (approx. 7kb minified/compressed) library designed to create fluid and smooth transitions between website pages. It enables a website to behave like a Single Page Application (SPA), reducing delays between page loads, minimizing HTTP requests, and enhancing the overall user experience through seamless transitions.
Key features of Barba.js
mainBarba provides several features for building high-quality web experiences:
- Simplified API: Written in TypeScript and utilizes
Promises. - DOM Flexibility: Supports custom markup, namespaces, and
dataattribute schemas. - Hook System: Provides lifecycle methods for
TransitionsandViews. - Transition Resolution: Uses
rulesto select the appropriate transition. - Sync Mode: Allows
leaveandenterhooks to play together. - Page Related Code: Enables attaching custom logic to specific
Views. - Plugin System: Extensible architecture with various available plugins.
- Built-in Utilities: Includes a collection of useful methods for developers.
- Simplified API: Written in TypeScript and utilizes
Install @barba/core
mainYou can install the core package of Barba using npm or yarn. It is recommended to install it as a development dependency.
npm install --save-dev @barba/coreyarn add @barba/core --devInstall @barba/router
mainYou can install the
@barba/routerpackage using npm or yarn as a development dependency.npm install --save-dev @barba/routeryarn add @barba/router --devInstall @barba/css
mainYou can install the
@barba/csspackage using npm or yarn as a development dependency.npm install --save-dev @barba/cssyarn add @barba/css --devAccess Barba.js documentation and resources
mainTo learn how to use Barba.js, you can access the following resources:
- Official Website: https://barba.js.org/
- User Guide: Detailed instructions on installation and usage at https://barba.js.org/docs/getstarted/intro/
- Developer API: Technical reference for developers at https://barba.js.org/api/
- Showcase: Examples of websites built with Barba at https://barba.js.org/showcase/
- Learning Materials: Lessons, courses, and videos available in the useful links section.
Install @barba/prefetch
mainInstall the
@barba/prefetchpackage as a development dependency using npm or yarn to enable prefetching capabilities in your Barba.js project.npm install --save-dev @barba/prefetchUnderstand route parsing and resolution types
mainThe
@barba/routeruses several internal interfaces to handle the lifecycle of a route match:IRouteParsed: Represents a route after its path has been parsed into a regular expression and extracted keys. It contains thepath, the generatedregex, and thekeysarray.IRouteResolved: Represents a route that has been successfully matched to a specific location. It contains the route'snameand the extractedparams(dynamic segments from the URL).IRouteByName: A dictionary-like object where keys are route names and values areIRouteParsedobjects.
Access route data in Barba transitions
mainOnce
@barba/routeris installed, it injects arouteproperty into thecurrentandnextobjects of Barba's transition data. This allows you to access route information within hooks or transition lifecycle methods.Example usage in a hook:
barba.hooks.beforeEnter((data) => { const nextRoute = data.next.route; if (nextRoute && nextRoute.name === 'user') { console.log('Navigating to user:', nextRoute.params.id); } });// The 'route' property is added to current and next transition data // current.route: IRouteResolved | undefined // next.route: IRouteResolved | undefinedHow @barba/prefetch works
mainThe prefetch plugin uses an
IntersectionObserverto monitor links on the page.- Observation: When the plugin is initialized (or after a transition via the
afterhook), it scans therootelement for<a>tags. It usesrequestIdleCallbackto ensure the scanning process doesn't interfere with main thread performance. - Intersection: When a link enters the viewport (intersects), the plugin checks if the URL is already cached or marked for prefetching.
- Prefetching: If the link is valid and not already in the Barba cache, the plugin triggers a
barba.request()to fetch the page content and stores the resulting Promise in the Barba cache with the action'prefetch'and status'pending'. - Lifecycle: Once a link is observed and processed, it is unobserved to prevent redundant work.
Note: Prefetching will be automatically disabled if
barba.prefetchIgnoreorbarba.cacheIgnoreare enabled in your Barba core configuration.- Observation: When the plugin is initialized (or after a transition via the
Manage CSS-based transitions with @barba/css
mainThe
@barba/cssplugin automates the management of CSS classes during Barba.js transitions. It allows you to define transitions using CSS transitions by automatically adding and removing specific classes to the container elements at different stages of the transition lifecycle.How it works
The plugin hooks into the Barba lifecycle and applies classes based on a
prefix(defaults tobarba). For a given transitionkind(e.g.,leave,enter,once), the plugin manages the following class states:- Initial State: Adds
{prefix}-{kind}and then{prefix}-{kind}-active. - Next Frame State: Removes
{prefix}-{kind}and adds{prefix}-{kind}-to. - Final State: Removes
{prefix}-{kind}-toand{prefix}-{kind}-active.
If the container has a CSS
transition-durationgreater than0s, the plugin will automatically wait for thetransitionendevent before proceeding to the next stage of the Barba transition.Customizing the Prefix
By default, the plugin uses the
barbaprefix. However, it will automatically use thenameproperty defined in your Barba transition object as the CSS prefix. For example, if your transition is namedfade, the classes applied will befade-leave,fade-leave-active, etc.API Reference
add(el: HTMLElement, step: string): voidManually adds a CSS class with the current prefix to an element.
el.classList.add("${this.prefix}-${step}")remove(el: HTMLElement, step: string): voidManually removes a CSS class with the current prefix from an element.
el.classList.remove("${this.prefix}-${step}")// Example of how classes are applied conceptually: // If prefix is 'barba' and kind is 'leave': // 1. barba-leave // 2. barba-leave-active // 3. barba-leave-to // 4. (transition ends) // 5. remove barba-leave-to, barba-leave-active- Initial State: Adds
Install and configure the @barba/prefetch plugin
mainThe
@barba/prefetchplugin preloads pages in the background when links enter the viewport, making transitions feel instantaneous.To use it, install the package and pass the
prefetchinstance tobarba.use(). You can configure the plugin via theIPrefetchOptionsobject during installation.Configuration Options
Option Type Default Description rootHTMLElement | HTMLDocumentdocument.bodyThe element within which to search for links to observe. timeoutnumber2000The timeout in milliseconds for the requestIdleCallbackused during observation.limitnumber0The maximum number of links to observe. If set to 0, all valid links are observed.import barba from '@barba/core'; import prefetch from '@barba/prefetch'; barba.use(prefetch, { root: document.querySelector('.content'), timeout: 3000, limit: 10 }); barba.init();