📜 Next.js Script Component ka Use

🔍 Script Component Kya Hai?

next/script ka component hota hai third-party JS files ko load karne ke liye (jaise Google Analytics, Ads, etc.) optimized way mein.

⚡ Kyun Use Karte Hain?

  • ✅ Better performance: Lazy loading and optimized inject hota hai.
  • ✅ Control: Kab aur kaise script load ho, control kar sakte hain.
  • ✅ No layout shift: Scripts delay nahi karte rendering ko.

⏰ Kab Use Karna Chahiye?

  • 🧠 Jab aapko koi external JS library add karni ho.
  • 📊 Google Analytics, Ads, Stripe, PayPal jaise tools mein.
  • 🎯 Jab aap specific route ya component pe hi load karwana chahte ho script.

🛠 Kaise Use Karte Hain?

import Script from 'next/script';

export default function MyComponent() {
    return (
        <>
            <h1>Google Analytics Example</h1>

            {/* ✅ External Script (Lazy Load) */}
            <Script
                src="https://www.google-analytics.com/analytics.js"
                strategy="lazyOnload"
                onLoad={() => console.log("✅ Google Analytics script loaded!")}
            />

            {/* ✅ Script from Public Folder */}
            <Script src="/myscript.js" strategy="afterInteractive" />

            {/* ✅ Inline Script */}
            <Script
                id="custom-inline-script"
                strategy="afterInteractive"
                dangerouslySetInnerHTML={{
                    __html: console.log("✅ Inline script executed after hydration!");
                }}
            />
        </>
    );
}
💡 strategy prop: Yeh batata hai script kab run kare:
  • beforeInteractive – Render se pehle (rarely use)
  • afterInteractive – Page load ke baad (⚡ recommended)
  • lazyOnload – Sab kuch load hone ke baad