Guides

Bundling Remote Scripts

Optimize third-party scripts by bundling them with your app.

Background

When you use scripts from other sites on your website, you rely on another server to load these scripts. This can slow down your site and raise concerns about safety and privacy.

Common problems

  • Slower website because it takes time to connect to other servers.
  • Safety risks if the other server is hacked.
  • Your visitors' data being used inappropriately by other servers.
  • Ad blockers or privacy tools might stop these scripts from working.

How to fix it

By bundling these scripts, you can host them yourself, which helps avoid these issues and keeps your site running smoothly.

How it Works

During the build process, your code is checked to find any instances of useScript that need to be bundled.

When a script is identified for bundling, it's downloaded and saved as a public asset at /_scripts/[hash].js. Here, [hash] represents the hash of the script's URL.

Important points about bundling:

  1. You need to have static values for your script URLs and bundling settings.
// GOOD - Static values allow for bundling
useScript('https://example.com/script.js', {
  bundle: true
})
// BAD - Dynamic values prevent bundling
useScript(scriptSrc, {
  bundle: canBundle
})
  1. If the original script changes without a URL change, the bundled version won't update in the browser cache. To handle this, use a versioned URL or a cache-busting query parameter.

Usage

Scripts can be bundled individually or on a global scale using specific settings.

Script Options

To decide if an individual script should be bundled, use the bundle option.

// Opt-in to bundle this specific script
useScript('https://example.com/script.js', {
  bundle: true,
})

Global Bundling

Adjust the default behavior for all scripts using the Nuxt Config. This example sets all scripts to be bundled by default.

nuxt.config.ts
export default defineNuxtConfig({
  scripts: {
    defaultScriptOptions: {
      bundle: true,
    }
  }
})

Limitations of Bundling

While many scripts can be bundled, there are exceptions you need to be aware of.

For instance, certain scripts:

  • Require tracking all user interactions for security reasons, like fraud detection (e.g., Stripe).
  • Must be served directly from their original source to function properly (e.g., Fathom Analytics).

Scripts from known registries are pre-configured to either allow or disallow bundling. For your own scripts, you'll need to decide whether bundling is appropriate on a case-by-case basis.

Change Asset Behavior

Use the assets option in your configuration to customize how scripts are bundled, such as changing the output directory for the bundled scripts.

nuxt.config.ts
export default defineNuxtConfig({
  scripts: {
    assets: {
      prefix: '/_custom-script-path/',
    }
  }
})

More configuration options will be available in future updates.