Barba.js

repository·main·Indexed 12 days ago

https://github.com/barbajs/barba

A 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.

Tokens
5.9K
Snippets
27
Records
32
Agent score
96%

What's inside Barba.js

  1. Overview of Barba.js

    main
    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.
  2. Key features of Barba.js

    main

    Barba provides several features for building high-quality web experiences:

    • Simplified API: Written in TypeScript and utilizes Promises.
    • DOM Flexibility: Supports custom markup, namespaces, and data attribute schemas.
    • Hook System: Provides lifecycle methods for Transitions and Views.
    • Transition Resolution: Uses rules to select the appropriate transition.
    • Sync Mode: Allows leave and enter hooks 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.
  3. Access Barba.js documentation and resources

    main

    To learn how to use Barba.js, you can access the following resources:

  4. Understand route parsing and resolution types

    main

    The @barba/router uses 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 the path, the generated regex, and the keys array.
    • IRouteResolved: Represents a route that has been successfully matched to a specific location. It contains the route's name and the extracted params (dynamic segments from the URL).
    • IRouteByName: A dictionary-like object where keys are route names and values are IRouteParsed objects.
  5. Access route data in Barba transitions

    main

    Once @barba/router is installed, it injects a route property into the current and next objects 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 | undefined
  6. How @barba/prefetch works

    main

    The prefetch plugin uses an IntersectionObserver to monitor links on the page.

    1. Observation: When the plugin is initialized (or after a transition via the after hook), it scans the root element for <a> tags. It uses requestIdleCallback to ensure the scanning process doesn't interfere with main thread performance.
    2. Intersection: When a link enters the viewport (intersects), the plugin checks if the URL is already cached or marked for prefetching.
    3. 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'.
    4. Lifecycle: Once a link is observed and processed, it is unobserved to prevent redundant work.

    Note: Prefetching will be automatically disabled if barba.prefetchIgnore or barba.cacheIgnore are enabled in your Barba core configuration.

  7. Manage CSS-based transitions with @barba/css

    main

    The @barba/css plugin 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 to barba). For a given transition kind (e.g., leave, enter, once), the plugin manages the following class states:

    1. Initial State: Adds {prefix}-{kind} and then {prefix}-{kind}-active.
    2. Next Frame State: Removes {prefix}-{kind} and adds {prefix}-{kind}-to.
    3. Final State: Removes {prefix}-{kind}-to and {prefix}-{kind}-active.

    If the container has a CSS transition-duration greater than 0s, the plugin will automatically wait for the transitionend event before proceeding to the next stage of the Barba transition.

    Customizing the Prefix

    By default, the plugin uses the barba prefix. However, it will automatically use the name property defined in your Barba transition object as the CSS prefix. For example, if your transition is named fade, the classes applied will be fade-leave, fade-leave-active, etc.

    API Reference

    add(el: HTMLElement, step: string): void

    Manually adds a CSS class with the current prefix to an element. el.classList.add("${this.prefix}-${step}")

    remove(el: HTMLElement, step: string): void

    Manually 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
  8. Install and configure the @barba/prefetch plugin

    main

    The @barba/prefetch plugin preloads pages in the background when links enter the viewport, making transitions feel instantaneous.

    To use it, install the package and pass the prefetch instance to barba.use(). You can configure the plugin via the IPrefetchOptions object during installation.

    Configuration Options

    OptionTypeDefaultDescription
    rootHTMLElement | HTMLDocumentdocument.bodyThe element within which to search for links to observe.
    timeoutnumber2000The timeout in milliseconds for the requestIdleCallback used 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();