
Script Component in NextJS
🚀 Script Component in Next.js
The next/script
component in Next.js helps load external and inline scripts efficiently, ensuring better performance and SEO.
📌 1. Why Use <Script>
?
✔️ Optimizes script loading for faster page performance
✔️ Supports lazy loading and priority execution
✔️ Prevents render-blocking issues
📌 2. Importing the Script
Component
import Script from "next/script";export default function Home() { return ( <> </> );}
✅ Loads the script without blocking page rendering
📌 4. Script Loading Strategies
The strategy
prop controls when the script is executed.
Strategy | Description | Use Case |
---|---|---|
beforeInteractive | Loads before hydration | Essential scripts (e.g., authentication) |
afterInteractive | Loads after hydration (default) | Analytics, tracking |
lazyOnload | Loads after the page is fully loaded | Non-essential scripts |
🔹 beforeInteractive
: High-Priority Scripts
Loads before React hydrates the page.
<Script src="https://example.com/auth.js" strategy="beforeInteractive" />
✅ Use for authentication or critical scripts
🔹 afterInteractive
: Default Behavior
Executes after the page is interactive.
<Script src="https://example.com/analytics.js" strategy="afterInteractive" />
✅ Best for analytics (Google Analytics, Facebook Pixel, etc.)
🔹 lazyOnload
: Lowest Priority
Loads after the page fully loads.
<Script src="https://example.com/non-critical.js" strategy="lazyOnload" />
✅ Good for chat widgets, ads, or heavy third-party scripts
📌 5. Inline Scripts (dangerouslySetInnerHTML
)
You can add inline scripts safely using Next.js.
<Script id="custom-inline-script" dangerouslySetInnerHTML={{ __html: `console.log("Hello from inline script!");`, }}/>
✅ Good for small tracking codes or inline JavaScript
📌 6. Example: Adding Google Analytics
import Script from "next/script";export default function Analytics() { return ( <> <Script </Script> </> );}
✅ Ensures Google Analytics loads efficiently
📌 7. Summary: Choosing the Right Strategy
Use Case | Strategy | Example |
---|---|---|
Authentication | beforeInteractive | Login scripts |
Analytics (GA, Facebook Pixel) | afterInteractive | Google Analytics |
Ads, Chat Widgets | lazyOnload | Chatbots, remarketing pixels |