Script loading is critical to web development because it directly affects website performance, influencing user experience and SEO.
The main thread parses HTML, executes JavaScript, and renders page content. Since JavaScript is inherently blocking, the browser must pause other tasks until the script is downloaded and executed.
<script> in <head>: Highly critical scripts<link rel="preload"> + <script async>: Medium to high priority scripts<script async>: Non-critical scripts<script defer>: Low priority scripts<script> at end of <body>: Lowest priority scriptsNext.js provides the next/script component to simplify and optimize script handling.
For scripts that must run before the page becomes interactive. Scripts are embedded directly into server-rendered HTML.
import Script from 'next/script';
<Script
strategy="beforeInteractive"
src="/path/to/bot-detector.js"
/>
Use Cases: Critical third-party integrations (Stripe, PayPal), security measures (CSP).
Loads scripts right after the page becomes interactive. Injected on the client side after hydration.
import Script from 'next/script';
<Script
strategy="afterInteractive"
src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
/>
Use Cases: Analytics (Google Analytics, Facebook Pixel), live chat (Intercom, Drift), feedback tools (Hotjar).
Loaded during browser's idle time using requestIdleCallback.
import Script from 'next/script';
<Script
strategy="lazyOnload"
src="/path/to/social-media-widget.js"
/>
Use Cases: Social media widgets, ad scripts, additional multimedia content.
The @next/third-parties library simplifies integrating popular third-party scripts:
import { GoogleTagManager, GoogleAnalytics } from "@next/third-parties/google";
import { YouTubeEmbed } from "@next/third-parties/youtube";
next/Script simplifies adding and managing scripts in Next.js.beforeInteractive loads scripts before the page becomes interactive.afterInteractive loads scripts after the page becomes interactive.lazyOnload loads scripts in the background after the page fully loads.