Topic 36 of 39
Script Optimization
Overview
The next/script component allows you to control exactly when third-party scripts (like analytics, ads, or widgets) load, ensuring they don't block the main thread and slow down your application.
Syntax
tsx
import Script from 'next/script';
export default function Layout() {
return (
<>
{/* Strategy dictates when the script loads */}
<Script
src="https://example-analytics.com/script.js"
strategy="lazyOnload"
/>
</>
);
}Common Pitfalls
- Using standard
<script>tags inlayout.tsx, which can block hydration or page rendering. - Using
strategy='beforeInteractive'for non-essential scripts (like Google Analytics). It should only be used for critical scripts like bot detectors.
Interview Questions
Q:
What is the default loading strategy for the Next.js
<Script> component?A:
The default strategy is afterInteractive, which loads the script immediately after the page becomes interactive (after hydration). This balances functionality and performance.
Real-World Example
Loading a heavy chat widget only during browser idle time to preserve performance.
example
tsx
<Script
src="https://heavy-chat-widget.com/embed.js"
strategy="lazyOnload"
/>Check Your Knowledge
Test your understanding of Script Optimization with these quick questions.