typescriptbeginner
Script Component Loading Strategies
Load third-party scripts efficiently with next/script using different loading strategies.
typescriptPress ⌘/Ctrl + Shift + C to copy
// app/layout.tsx
import Script from 'next/script';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
{children}
{/* beforeInteractive — loads before page hydration */}
<Script
src="https://cdn.polyfill.io/v3/polyfill.min.js"
strategy="beforeInteractive"
/>
{/* afterInteractive (default) — loads after hydration */}
<Script
src="https://www.googletagmanager.com/gtag/js?id=G-XXXX"
strategy="afterInteractive"
/>
<Script id="gtag-init" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXX');
`}
</Script>
{/* lazyOnload — loads during idle time */}
<Script
src="https://cdn.chatwidget.com/widget.js"
strategy="lazyOnload"
onLoad={() => console.log('Chat widget loaded')}
/>
{/* worker — loads in web worker (experimental) */}
<Script
src="https://analytics.example.com/tracker.js"
strategy="worker"
/>
</body>
</html>
);
}
// Using onLoad and onError callbacks
// <Script
// src="https://maps.googleapis.com/maps/api/js"
// onLoad={() => initMap()}
// onError={(e) => console.error('Failed to load maps', e)}
// />Use Cases
- analytics
- chat widgets
- third-party integrations
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Next.js Streaming with Suspense
Stream server components with Suspense boundaries for progressive page loading and better TTFB.
Best for: Progressive loading for data-heavy dashboards
#nextjs#streaming
typescriptbeginner
Next.js Image Optimization Patterns
Advanced next/image usage with responsive sizes, blur placeholders, and custom loaders.
Best for: Optimizing Core Web Vitals with proper image loading
#nextjs#image
typescriptbeginner
Loading UI with Skeleton Screens
Create loading.tsx skeleton screens for instant navigation feedback with Next.js App Router.
Best for: Route transition loading states
#nextjs#loading
typescriptadvanced
Caching Strategies in Next.js
Master Next.js caching with fetch cache, unstable_cache, revalidatePath, and revalidateTag patterns.
Best for: ISR page caching
#nextjs#caching