Skip to content

How to Add Smart Prefetch to Any Website Using Universal JavaScript Integration

universal-javascript

Welcome to the definitive guide for implementing Smart Prefetch. This document provides everything you need to know, from initial setup to advanced configuration and performance monitoring, to supercharge your website’s navigation speed.


1. Introduction

In today’s fast-paced digital world, website speed is not a luxury; it’s a necessity. Milliseconds can mean the difference between a conversion and a bounce. Smart Prefetch is a service that uses AI-based predictions to prefetch the next most likely page before a user clicks—boosting speed, improving user experience, and helping to increase revenue.

This guide focuses on the Universal JavaScript integration, a cutting-edge solution designed to make your website feel instant by adding a single line of code.

Benefits: The Need for Speed

Implementing Smart Prefetch offers tangible benefits that directly impact your users and your business goals:

  • Dramatically Faster Page Loading: By fetching assets before they are explicitly requested, navigations become seamless and instantaneous. This eliminates the “blank screen” wait time that frustrates users.
  • Vastly Improved User Experience (UX): A responsive, snappy website feels more professional and satisfying to use. This leads to increased user engagement, longer session durations, and more positive brand perception.
  • Significantly Reduced Bounce Rates: Users are less likely to abandon your site when pages load instantly. Smart Prefetch directly combats bounce rates caused by loading friction, keeping potential customers on your site.

How It Works: Predictive AI and Speculation Rules

The magic behind Smart Prefetch lies in its two-stage process:

  1. AI-Powered Prediction: The script analyzes user behavior in real-time—such as mouse movements, hover duration, and on-page engagement patterns—to predict the most likely next navigation with a high degree of confidence.
  2. Speculation Rules API: Once a likely target is identified, the script dynamically injects instructions using the modern Speculation Rules API. This is a safe, standardized browser feature that tells the browser to prefetch the specified URL(s) during idle time, without blocking the main thread or competing for critical resources.

Universal Compatibility

One of the most powerful features of this integration is its universal nature. While we offer dedicated plugins for platforms like WordPress and Shopify for the easiest setup, the universal script is framework-agnostic and designed to work out-of-the-box with any other technology stack.

  • JavaScript Frameworks: React, Vue.js, Angular, Svelte, etc.
  • Static Site Generators (SSG): Jekyll, Hugo, Gatsby, Next.js, Eleventy, etc.
  • E-commerce Platforms: Magento, BigCommerce (with theme access).
  • Plain Old HTML, CSS & JavaScript: The foundational technologies of the web.

Quick Summary: Introduction

Smart Prefetch is a service that uses AI to predict and preload user navigations. This results in instant page loads, better UX, and lower bounce rates. This guide covers the universal script for custom websites, while dedicated plugins exist for platforms like WordPress and Shopify.


2. Prerequisites

Before you get started, please ensure you meet the following requirements. The process is straightforward, but having these in place will guarantee a smooth installation.

  • Modern Browser Support: The core technology relies on the Speculation Rules API. For prefetching to occur, users must be on a supported browser. As of July 2025, this includes:
    • Google Chrome 109+
    • Microsoft Edge 109+
    • Safari 17+
    • Note: The script is completely inert and has zero performance impact on older, unsupported browsers. It simply won’t execute.
  • Basic Understanding of HTML: You should be familiar with the basic structure of an HTML document, specifically the <head> and <body> tags, and know how to add a <script> element.
  • Access to Edit Website Files: You must have the ability to edit your website’s core HTML or template files. This could mean accessing an index.html file for a static site or a layout component in a JavaScript framework.
  • Smart Prefetch Account: To activate the service and view analytics, you need a free account. You can create one in seconds at the official dashboard:

Quick Summary: Prerequisites

You need access to edit your site’s HTML, a basic understanding of HTML, and a free Smart Prefetch account. The feature works on modern browsers like Chrome, Edge, and Safari.


3. Quick Start Guide

You can get Smart Prefetch up and running on your website in under five minutes by following these simple steps.

  1. Step 1: Create Account at Smart Prefetch DashboardNavigate to https://dash.smartprefetch.link/ and sign up. It’s a quick, free process that only requires a valid email address.
  2. Step 2: Add Your Website DomainOnce logged into your new dashboard, you’ll be prompted to add a new property. Enter your website’s full domain name (e.g., my-awesome-site.com). This links your site to your account for analytics and configuration.
  3. Step 3: Copy the Universal Script SnippetAfter adding your domain, the dashboard will display the universal JavaScript snippet. This single line of code is all you need. Click the “Copy” button to get it onto your clipboard.
  4. Step 4: Add Script to Your WebsitePaste the copied <script> tag into your website’s HTML. The recommended location is just before the closing </head> tag. (See Section 4 for detailed platform-specific instructions).
  5. Step 5: Verify InstallationDeploy your changes. Open your live website in a supported browser (like Chrome) and use the Developer Tools to confirm the script is loading and prefetching is active. (See Section 5 for detailed verification steps).

Quick Summary: Quick Start

Sign up at the dashboard, add your domain, copy the script, paste it into your site’s <head>, and verify the installation using browser developer tools.


4. Universal Script Installation

This section provides detailed guidance on where and how to install the script snippet across various platforms and frameworks.

4.1 The Script Code

This is the one and only script you need for a universal installation. It’s designed to be lightweight, asynchronous, and non-blocking.

HTML

<script src="https://speculation-rules.smartprefetch.link/index.min.js" async></script>

4.2 Where to Place the Script

Proper placement is key to optimal performance.

  • Recommended Placement: Before closing </head> tagThis is the ideal location. Placing the script in the <head> allows the browser to discover and begin fetching the script early in the page load process. Because it has the async attribute, it will not block the rendering of your page content.
  • Alternative Placement: Before closing </body> tagThis is also a valid placement. It ensures all DOM elements are rendered before the script is fetched and executed. However, it may slightly delay the script’s initialization, meaning it might miss the earliest opportunities to prefetch.
  • Why the async attribute is important:The async attribute is crucial. It tells the browser to download the script in the background without pausing HTML parsing. Once downloaded, the script will execute. This prevents the Smart Prefetch script from ever slowing down your initial page render, ensuring it only enhances performance, never detracts from it.

4.3 Installation Methods by Platform

Here are copy-paste ready examples for the most popular web development platforms.

WordPress and WooCommerce

For WordPress and WooCommerce sites, we offer a dedicated plugin for the easiest and most optimized integration. Manual script installation is not recommended.

Please follow our step-by-step WordPress installation guide here:

Shopify

For Shopify stores, we provide a streamlined setup process that integrates perfectly with the Shopify ecosystem and theme structure.

Please follow our complete Shopify setup guide here:

Static HTML Websites

For a standard HTML website, open your index.html file (and any other primary layout/template files) and paste the script into the <head> section.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Awesome Website</title>
    
    <script src="https://speculation-rules.smartprefetch.link/index.min.js" async></script>
</head>
<body>
    <h1>Welcome!</h1>
    <a href="/about.html">Learn More About Us</a>
</body>
</html>

React Applications

In a standard Create React App (CRA) setup, the best place to add scripts is the public/index.html file. Alternatively, for more dynamic control, you can use a library like react-helmet.

Method 1: public/index.html (Recommended for simplicity)

HTML

<head>
    <meta charset="utf-8" />
    <title>My React App</title>
    <script src="https://speculation-rules.smartprefetch.link/index.min.js" async></script>
</head>

Method 2: Using react-helmet or react-helmet-async

JavaScript

// In a top-level component like App.js
import { Helmet } from 'react-helmet-async'; // Or 'react-helmet'

function App() {
  return (
    <div>
      <Helmet>
        <title>My Awesome React App</title>
        {/* Helmet injects this script into the document head */}
        <script src="https://speculation-rules.smartprefetch.link/index.min.js" async />
      </Helmet>
      {/* The rest of your app's components and routes */}
    </div>
  );
}

Vue.js Applications

Similar to React, you can either modify the main public/index.html file or use a meta-management library.

Method 1: public/index.html (Recommended)

HTML

<head>
  <meta charset="utf-8">
  <title>my-vue-app</title>
  <script src="https://speculation-rules.smartprefetch.link/index.min.js" async></script>
</head>

Angular Applications

For Angular apps created with the Angular CLI, the correct place to add global scripts is the src/index.html file.

HTML

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyAngularApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <script src="https://speculation-rules.smartprefetch.link/index.min.js" async></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

Jekyll / GitHub Pages

In a Jekyll project, add the script to your main layout file, typically _layouts/default.html or _includes/head.html.

HTML

<head>
  <script src="https://speculation-rules.smartprefetch.link/index.min.js" async></script>
</head>

Hugo Static Site Generator

For Hugo sites, edit the partial template for the <head> section, usually located at layouts/partials/head.html.

HTML

<head>
    <script src="https://speculation-rules.smartprefetch.link/index.min.js" async></script>
</head>

Gatsby

Using gatsby-ssr.js is the most robust method for adding scripts in Gatsby.

JavaScript

// In your project root, create or edit gatsby-ssr.js
import React from 'react';

export const onRenderBody = ({ setHeadComponents }) => {
  setHeadComponents([
    <script
      key="smart-prefetch" // A unique key for React
      src="https://speculation-rules.smartprefetch.link/index.min.js"
      async
    />
  ]);
};

Next.js

In Next.js, use the custom _document.js (or .tsx) file to modify the <head> tag.

JavaScript

// In pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          <script src="https://speculation-rules.smartprefetch.link/index.min.js" async />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

Quick Summary: Installation

For WordPress and Shopify, use our dedicated guides for plugin-based installation. For all other platforms, place the single <script> tag with the async attribute just before the closing </head> tag.


5. Verification and Testing

After installing the script, it’s crucial to verify that it’s working as expected. Use your browser’s developer tools for a thorough check.

5.1 Browser Developer Tools Check

A quick way to see if the script has loaded and initialized is by using the browser’s JavaScript console.

  1. Open your website in Chrome or Edge.
  2. Right-click and select “Inspect” to open Developer Tools.
  3. Go to the Console tab.
  4. Type the following commands and press Enter:

JavaScript

// This command checks if the main script object has been initialized.
// It should return 'true' if the script loaded successfully.
console.log('Smart Prefetch loaded:', !!window.smartPrefetch);

// This command looks for the <script type="speculationrules"> tag that
// the library injects into the page. It should return a NodeList containing one or more elements.
console.log('Speculation rules:', document.querySelectorAll('script[type="speculationrules"]'));

If the first command returns true and the second shows a NodeList, your script has been successfully installed and initialized.

5.2 Network Tab Verification

This is the definitive test to see prefetching in action.

  1. In Developer Tools, switch to the Network tab.
  2. Clear any existing requests by clicking the clear icon (🚫).
  3. On your webpage, hover your mouse over an internal link.
  4. Watch the Network tab. You should see a new request appear for the URL of the link you hovered over.

What to look for:

  • Initiator: The Initiator column should show speculation rules or the script name itself.
  • Size: The size might show (prefetch cache) or a disk size.
  • Headers: Click on the request and look at the Headers tab. You should find a request header Sec-Purpose: prefetch. This is the clearest indicator.

5.3 Dashboard Analytics

Your Smart Prefetch dashboard provides insights into its real-world impact.

  • Accessing Your Dashboard: Log in at https://dash.smartprefetch.link/.
  • Viewing Prediction Reports: The dashboard will show which pages are most frequently prefetched.
  • Understanding KPI Metrics: Track KPIs like Prefetch Hit Rate, Average Time Saved, and Bandwidth Utilized.

Quick Summary: Verification

Use the browser console to check for window.smartPrefetch and speculationrules scripts. Use the Network tab to observe requests with the Sec-Purpose: prefetch header. Finally, check your dashboard for performance analytics and KPIs.


6. Advanced Configuration

For users who need more granular control, Smart Prefetch can be configured with a global JavaScript object.

6.1 Custom Configuration Options

To use custom settings, you must place a <script> tag with a window.smartPrefetchConfig object before the main Smart Prefetch script tag.

Example Implementation:

HTML

<head>
    <script>
      window.smartPrefetchConfig = {
        // The maximum number of URLs to prefetch on a given page. Default is 5.
        maxPredictions: 10,

        // The AI's minimum confidence score (0.0 to 1.0) required to trigger a prefetch.
        // Higher values mean fewer, but more accurate, prefetches. Default is 0.5.
        confidenceThreshold: 0.65,

        // An array of URL path patterns to exclude from prefetching.
        // Useful for logout links, admin panels, or transactional pages.
        excludePatterns: ['/admin/', '/checkout/', '/logout', '/cart/add']
      };
    </script>

    <script src="https://speculation-rules.smartprefetch.link/index.min.js" async></script>
</head>

Quick Summary: Advanced Config

Create a window.smartPrefetchConfig object in a <script> tag placed before the main script to customize behavior. You can control the number of predictions, the AI confidence threshold, and URL exclusion patterns.


7. Troubleshooting Guide

Even with a simple installation, issues can sometimes arise. This guide covers the most common problems and their solutions.

7.1 Common Issues and Solutions

  • Issue: Script is not loading.
    • Solution: Check your browser’s Network tab to see if the script is being loaded. Check for blockers like ad-blocking extensions or firewalls that may be interfering.
  • Issue: No prefetch activity is visible in the Network tab.
    • Solution: Verify you are on a supported browser. Check the browser console for any JavaScript errors that could be halting execution. Ensure your domain is correctly added in the Smart Prefetch dashboard.
  • Issue: Conflicts with other performance tools.
    • Solution: If you are using another prefetching library (like instant.page), you should disable it to prevent conflicts.
  • Issue: My site uses a strict Content Security Policy (CSP).
    • Solution: You must whitelist the Smart Prefetch script’s domain in your CSP. Add https://speculation-rules.smartprefetch.link to your script-src directive. Learn more about CSP on MDN Web Docs.
    • Example CSP Directive:Content-Security-Policy: script-src ‘self’ https://speculation-rules.smartprefetch.link;

7.3 Performance Considerations

  • Impact on Page Load Speed: None. The script is loaded with async, so it does not block page rendering.
  • Server Resource Usage: Minimal. Prefetch requests are low-priority and should not strain a well-configured server or CDN.
  • Mobile Device Considerations: Smart Prefetch is conscious of mobile data usage and respects the Save-Data client hint header to reduce prefetching when necessary.

Quick Summary: Troubleshooting

If the script isn’t working, check for network errors, browser support, and console logs. Disable other prefetching libraries. If you use a CSP, you must whitelist the script’s domain.


8. Best Practices

To get the most out of Smart Prefetch, follow these implementation guidelines.

8.1 Implementation Guidelines

  • Exclude Action-Oriented Links: Always use excludePatterns or the data-smart-prefetch-ignore attribute on links that trigger an action, such as /logout, /add-to-cart, /delete-post, or anything in an /admin/ section.
  • Single Page Application (SPA) Integration: For SPAs, Smart Prefetch will prefetch the necessary JavaScript bundles for the target route, speeding up virtual page transitions.
  • E-commerce Considerations: Prefetching product and category pages is great for UX. Be vigilant about excluding checkout, payment, and cart modification links.

8.2 Performance Optimization

  • Combine with Other Tools: Smart Prefetch is a powerful addition to a holistic performance strategy that includes image optimization, minification, and effective caching policies.
  • Cache Considerations: Ensure your server sends appropriate Cache-Control headers for your HTML documents to allow the browser to store prefetched assets efficiently.

Quick Summary: Best Practices

Exclude links that perform actions. Combine Smart Prefetch with other optimizations like image compression and caching for maximum impact.


9. Monitoring and Analytics

Your dashboard is the central hub for understanding performance.

9.1 Dashboard Usage

Log into https://dash.smartprefetch.link/ to access your analytics, view prediction reports, track KPIs, and manage billing.

9.2 Performance Metrics

  • How to Measure Improvement:
  • A/B Testing Considerations: For a rigorous analysis, conduct an A/B test by serving the script to a portion of your users and comparing their engagement metrics against a control group.

Quick Summary: Monitoring

Use the dashboard to track KPIs. Measure impact by observing changes in Core Web Vitals (especially INP), bounce rates, and user session data.


10. FAQ Section

Here are answers to some of the most frequently asked questions.

  • Does it work with all browsers?It provides prefetching on modern browsers like Chrome, Edge, and Safari. On other browsers, it does nothing and has no performance cost.
  • Will it slow down my website?No. The script is tiny, loaded asynchronously, and prefetching happens during browser idle time, so it never blocks page rendering or competes with critical resources.
  • How does billing work?Smart Prefetch offers a generous free tier for smaller sites, with paid plans available for high-traffic websites. Check the dashboard at https://smartprefetch.link/ for current plans.
  • Can I use it with WordPress/Shopify?Yes! We offer dedicated, easy-to-use plugins for WordPress and Shopify for the best integration. Please see our platform-specific guides in Section 4.3.
  • What about SEO impact?The impact is positive. Site speed is a known ranking factor. By improving your Core Web Vitals and user experience signals, you send positive signals to search engines.
  • What about privacy and GDPR considerations?Smart Prefetch is privacy-focused. It does not use cookies or track users across websites. The prediction is based on anonymous, on-page behavior within a single session and is GDPR compliant.

11. Support and Resources

If you need help or want to learn more, use these resources.