Next.js Tutorial
- Next.js Introduction
- Next.js Installation
- Project Structure
- Pages & Routing
- Dynamic Routing
- Linking & Navigating
- Data Fetching (SSR)
- Data Fetching (SSG)
- Client-Side Rendering
- API Routes
- Layouts & Components
- Styling
- Image Optimization
- Font Optimization
- Script Optimization
- Middleware
- Environment Variables
- Error Handling
- Authentication
- React Server Components
- Server Actions
- Suspense & Streaming
- Caching & Revalidation
- TypeScript Integration
- Deployment
Script Optimization (`next/script`)
Almost every commercial website requires third-party scripts: Analytics (Google Analytics, Mixpanel), Customer Success (Zendesk, Intercom), Ads (Google AdSense), or Payments (Stripe.js).
Injecting these scripts heavily reduces page performance if loaded incorrectly. Next.js provides the next/script component to control the exact loading priority of these scripts.
The `next/script` Component
Instead of using the standard HTML <script> tag, import `Script` from Next.js.
import Script from 'next/script';
export default function Dashboard() {
return (
<>
<h1>Dashboard Analytics</h1>
<Script
src="https://example.com/analytics.js"
strategy="lazyOnload" // Priority configuration
/>
</>
);
}Script Strategies
The strategy prop defines exactly WHEN the script should load. Next.js offers four strategies:
| Strategy | When to Use It | Example Use Case |
|---|---|---|
beforeInteractive | Loads BEFORE Next.js code is injected. Halts page rendering. Use strictly. | Bot detectors, cookie consent managers. |
afterInteractive (Default) | Loads immediately after the page becomes interactive. | Tag Managers, Analytics. |
lazyOnload | Loads during browser idle time, preserving pure performance. | Customer support chat widgets, social media plugins. |
worker (Beta) | Loads via a Background Web Worker, offloading from the main thread entirely. | Heavy analytical suites. |
Inline Scripts
If you need to execute raw JavaScript instead of loading an external URL, you can place the JS inside the `Script` component, and supply a unique `id` so Next.js can track it.
import Script from 'next/script';
export default function TrackingPage() {
return (
<>
<Script id="show-banner" strategy="afterInteractive">
{`document.getElementById("banner").classList.remove("hidden");`}
</Script>
<div id="banner" className="hidden">Welcome to tracking!</div>
</>
);
}Conclusion
With `next/script`, your high-priority items load first, and your heavy chat bots load last, ensuring your users never feel sluggish performance. Now let's dive into some hardcore routing tools—Middleware.