Guess.js Documentation

repository·master·Indexed 27 days ago

https://github.com/guess-js/guess

A collection of libraries and tools for enabling data-driven user experiences through predictive fetching and bundling based on user navigation patterns. It includes guess-ga for Google Analytics data retrieval, guess-parser for extracting application routes, and a GuessPlugin for Webpack to automate bundle prefetching. It also provides a guess-static-sites experiment for non-Webpack sites to implement predictive loading workflows.

Tokens
7K
Snippets
25
Records
53
Agent score
93%

What's inside Guess.js

  1. Overview of Guess.js

    master
    Guess.js is a collection of libraries and tools designed to implement predictive, data-analytics-driven approaches to web performance. It aims to reduce the friction of applying machine learning or analytics (like Google Analytics) to modern web applications to improve user experience through techniques like predictive prefetching and bundling.
  2. Quickstart for non-Webpack users

    master

    For sites not using Webpack, you can implement a data-driven loading workflow using the guess-static-sites experiment.

    This workflow uses Google Analytics data to determine the page a user is most likely to visit next. The process involves:

    1. Using Google Analytics data to identify navigation patterns.
    2. Adding a client-side script to your application.
    3. The script requests the next likely URL from a server and prefetches that resource.
  3. Quickstart for Webpack users

    master

    To enable data-driven bundling in a Webpack-based project, install and configure the GuessPlugin. This plugin automates the setup process for predictive fetching by consuming the ga and parser modules.

    If you prefer to use the modules individually instead of the plugin, you can use:

    • ga: Fetches structured data from the Google Analytics API to identify user navigation patterns.
    • parser: Provides JavaScript framework parsing, which powers the route-parsing capabilities used by the webpack plugin.
    • webpack: The plugin itself that manages predictive fetching configuration.
  4. Configure Automatic Prefetching

    master

    You can automate bundle prefetching by combining guess-webpack with guess-parser. This creates a mapping between paths and lazy-loaded JavaScript bundles at build time. At runtime, Guess.js will automatically pick top paths and prefetch their bundles.

    Security Note: When using a JWT token for Google authentication, ensure your credentials.json is added to .gitignore.

    import { parseRoutes } from 'guess-parser';
    const credentials = require('./credentials.json');
    
    // Inside webpack config
    new GuessPlugin({
      jwt: credentials,
      GA: 'XXXXXX',
      routeProvider() {
        return parseRoutes('.');
      },
      runtime: {
        delegate: false
      }
    });
  5. React route parsing requirements

    master

    Because React lacks a standard route definition syntax, guess-parser only supports applications following specific conventions:

    1. Syntax: Only JSX syntax is supported.
    2. Router: Only react-router-like syntax is supported.
    3. Route Paths: The path attribute of the <Route/> element must be a string literal.
    4. Lazy Loading: Lazy-loaded components must use a dynamic import with a specific AST structure:
      • A CallExpression (e.g., AsyncComponent) with a single argument.
      • The argument must be an ArrowFunction.
      • The arrow function must have an expression body (e.g., a CallExpression).
      • The CallExpression must receive a StringLiteral pointing to the lazy-loaded module.
    <Router history={history}>
      <div className="App">
        <Link to="/intro">Intro</Link>
        <Link to="/main">Main</Link>
        <div>
          <Switch>
            <Redirect exact={true} from="/" to="/intro" />
            <Route path="/intro" component={AsyncComponent(() => import('./intro/Intro'))} />
            <Route path="/main" component={Main} />
          </Switch>
        </div>
      </div>
    </Router>
  6. Risks and Best Practices in Predictive Prefetching

    master

    When implementing predictive prefetching, consider the following risks:

    • Data Consumption: Be mindful of users on restricted data plans. Respect the Save-Data HTTP header.
    • Undesirable Pages: Avoid prefetching pages that trigger immediate actions (e.g., logout pages, one-click purchase buttons). Use a blacklist of URLs to prevent this.
    • Web Standards: Be aware of the transition from <link rel=prerender> to NoStatePrefetch. While rel=prefetch fetches a single resource, NoStatePrefetch runs the preload scanner on the resource to discover and prefetch subresources.
  7. Install and configure GuessPlugin for Webpack

    master

    To use Guess.js with Webpack, install the guess-webpack package and add the GuessPlugin to your Webpack configuration. The plugin requires a Google Analytics View ID to extract transition reports.

    Note: The guess-ga plugin will extract reports from Google Analytics for the last year by default.

  8. Automate prediction updates with cron jobs

    master

    It is recommended to set up a cron job to periodically run generatePredictions.js. This ensures prefetch links remain accurate as your site content and traffic patterns change.

    Note on Data Range: By default, the system uses the last 30 days of traffic. You can modify this value in src/queryParams.js. High-traffic sites may benefit from a shorter range (1-7 days), while low-traffic sites should stick to a longer range (30 days).

  9. Configure Google Analytics and Service Account credentials

    master

    To allow Guess.js to consume your Google Analytics data, follow these steps:

    1. Create a Service Account: In the Google APIs console, create a new Service Account with the role Service Account User and select P12 key as the key type.
    2. Generate PEM certificate: Move the downloaded .p12 file to the project directory and run: openssl pkcs12 -in *.p12 -out key.pem -nodes -clcerts
    3. Add Service Account to Google Analytics: In Google Analytics (Admin > User Management), add the service account email address with Read & Analyze permissions.
    4. Enable API: Enable the Google Analytics Reporting API.