Skip to main content

Command Palette

Search for a command to run...

Scripts in Next.js

Updated
2 min read
Scripts in Next.js

The Problem

  • Scripts can slow down page load

  • Different scripts need different loading priorities

  • Some scripts block rendering, others don't need to

The Solution

Basic Usage:

import Script from 'next/script'

// Basic usage
<Script src="https://example.com/script.js" />

// With strategy
<Script
  src="https://example.com/analytics.js"
  strategy="afterInteractive"
/>

Loading Strategies

1. beforeInteractive

  • Loads before page hydration

  • Use for critical scripts (bot detection, cookie consent)

  • Must be in root layout

  • Always injected in <head>

2. afterInteractive (default)

  • Loads after some hydration

  • Good for analytics, tag managers

  • Can be anywhere in the app

3. lazyOnload

  • Loads during browser idle time

  • Best for low-priority scripts

  • Chat widgets, social media embeds

4. worker (experimental)

  • Offloads to web worker

  • Keeps main thread free

  • Great for heavy third-party scripts

Real World Example

<Script
  id="google-analytics"
  strategy="afterInteractive"
  src="https://www.googletagmanager.com/gtag"
/>

Worker potential:

  • This analytics script could run in a worker instead

  • Benefits:

    • Main thread stays clean for user interactions

    • Doesn't compete with your app's JavaScript

    • Better performance metrics (Interaction to next paint (INP), Time to Interactive (TTI))

  • Especially valuable when you have many third-party scripts (analytics, tracking, ads)

The key difference: afterInteractive still runs on the main thread, potentially impacting performance, while worker isolates these scripts from your core app functionality.