LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 3813 min read

Script Optimization

Control exactly when third-party scripts load — analytics, chat widgets, ads — using the next/script component.

Why Third-Party Scripts Are Risky

A plain <script> tag in the wrong place can block the browser from rendering anything until it finishes downloading and executing — a slow analytics or chat-widget script can visibly delay your entire page for no good reason.

The Script Component

next/script gives you explicit control over when a script loads relative to the rest of the page, through its strategy prop.

import Script from 'next/script';
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Script src="https://widget.example.com/chat.js" strategy="lazyOnload" />
</body>
</html>
);
}

Loading Strategies

StrategyWhen It LoadsUse For
beforeInteractiveBefore any page JavaScript runsCritical scripts needed before hydration (rare — bot detection, polyfills)
afterInteractive (default)Right after the page becomes interactiveAnalytics, tag managers
lazyOnloadDuring idle browser time, after everything elseChat widgets, low-priority third-party embeds
worker (experimental)Off the main thread, in a web workerScripts that can run fully independently of the DOM
Default to lazyOnload for Non-Critical Scripts

Anything that isn't needed for the first meaningful paint — chat widgets, social embeds, most marketing pixels — should load as late as possible so it never competes with the content your visitor actually came for.

FAQs

No — next/script is specifically for scripts referenced inside your React components, not for building raw HTML/API responses.

It still works, but you lose the loading-strategy control and some of the automatic deduplication next/script provides.

Summary

next/script lets you decide exactly how aggressively a third-party script should compete for the browser's attention. Next, you'll look at Next.js's Metadata API for controlling SEO tags per page.

Next Lesson →

Metadata API & SEO