Design Converter
Education
Software Development Executive - II
Software Development Executive - I
Last updated on Jun 3, 2024
Last updated on May 31, 2024
Next.js, a powerful React framework, offers various features to optimize the loading and execution of scripts in web applications.
This guide delves into the technical aspects of handling scripts in Next.js, ensuring your applications remain efficient and performant.
The Script component in Next.js, available as next/script, is pivotal for managing scripts. This component enhances the loading and execution of scripts, providing several strategies to optimize performance and ensure critical scripts load efficiently.
To use the Script component, import it into your component or page:
1import Script from 'next/script'; 2 3export default function HomePage() { 4 return ( 5 <> 6 <h1>Welcome to My Site</h1> 7 <Script src="https://example.com/script.js" /> 8 </> 9 ); 10}
This code snippet demonstrates a simple inclusion of an external script.
The Script component offers four loading strategies:
beforeInteractive: Loads scripts before the page becomes interactive. Ideal for critical scripts like bot detectors.
afterInteractive: The default strategy, defers script loading until after the page becomes interactive.
lazyOnload: Loads scripts during browser idle time, perfect for low-priority scripts.
worker: Experimental feature to load scripts in a web worker.
Here's an example using different strategies:
1import Script from 'next/script'; 2 3export default function HomePage() { 4 return ( 5 <> 6 <h1>Welcome to My Site</h1> 7 <Script src="https://example.com/script1.js" strategy="beforeInteractive" /> 8 <Script src="https://example.com/script2.js" strategy="afterInteractive" /> 9 <Script src="https://example.com/script3.js" strategy="lazyonload" /> 10 </> 11 ); 12}
The Script component also supports event handlers like onLoad, onReady, and onError. These events help you execute code after a script has finished loading or handle errors when a script fails to load.
1import Script from 'next/script'; 2 3export default function HomePage() { 4 const handleLoad = () => { 5 console.log('Script has finished loading'); 6 }; 7 8 const handleError = () => { 9 console.error('Script failed to load'); 10 }; 11 12 return ( 13 <> 14 <h1>Welcome to My Site</h1> 15 <Script 16 src="https://example.com/script.js" 17 strategy="afterInteractive" 18 onLoad={handleLoad} 19 onError={handleError} 20 /> 21 </> 22 ); 23}
Next.js supports inline scripts, allowing you to inject small pieces of JavaScript directly into your pages. Inline scripts are useful for executing JS code that doesn't warrant a separate file.
1import Script from 'next/script'; 2 3export default function HomePage() { 4 return ( 5 <> 6 <h1>Welcome to My Site</h1> 7 <Script id="inline-script" strategy="afterInteractive"> 8 {` 9 console.log('Inline script executed'); 10 `} 11 </Script> 12 </> 13 ); 14}
Loading third-party scripts efficiently is crucial for performance. Next.js allows you to load third-party scripts with specific strategies to minimize their impact on your application's performance.
Google Tag Manager (GTM) is a common third-party script used for tracking. Here’s how you can load it using Next.js:
1import Script from 'next/script'; 2 3export default function HomePage() { 4 return ( 5 <> 6 <h1>Welcome to My Site</h1> 7 <Script src={`https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX`} strategy="afterInteractive" /> 8 </> 9 ); 10}
Critical scripts, necessary for rendering or functionality, should be loaded as soon as possible using the beforeInteractive strategy.
1import Script from 'next/script'; 2 3export default function Document() { 4 return ( 5 <Html> 6 <Head /> 7 <body> 8 <Main /> 9 <NextScript /> 10 <Script src="https://example.com/critical-script.js" strategy="beforeInteractive" /> 11 </body> 12 </Html> 13 ); 14}
Use Appropriate Strategies: Choose the right strategy (beforeInteractive, afterInteractive, lazyonload) based on the script's priority.
Defer Non-Critical Scripts: Use the lazyonload strategy for scripts that aren't essential for initial page load.
Handle Errors Gracefully: Always include onError handlers to manage script load failures.
The worker strategy is an experimental feature in Next.js that allows scripts to be loaded in a web worker. This can offload tasks from the main thread, improving performance and user experience. However, it's essential to note that not all scripts can be safely loaded in a web worker due to limitations in accessing the DOM.
Here's an example of using the worker strategy:
1import Script from 'next/script'; 2 3export default function HomePage() { 4 return ( 5 <> 6 <h1>Welcome to My Site</h1> 7 <Script src="https://example.com/worker-script.js" strategy="worker" /> 8 </> 9 ); 10}
To optimize third-party scripts, consider the following best practices:
1<link rel="preconnect" href="https://example.com"> 2<link rel="dns-prefetch" href="https://example.com">
1<Script src="https://example.com/non-critical-script.js" strategy="lazyonload" />
1<script src="https://example.com/async-script.js" async></script> 2<script src="https://example.com/defer-script.js" defer></script>
Google Analytics is a typical example of a third-party script that benefits from optimized loading. By using the afterInteractive strategy, you ensure it doesn't block the initial page load.
1import Script from 'next/script'; 2 3export default function HomePage() { 4 return ( 5 <> 6 <h1>Welcome to My Site</h1> 7 <Script 8 src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID" 9 strategy="afterInteractive" 10 /> 11 <Script id="google-analytics" strategy="afterInteractive"> 12 {` 13 window.dataLayer = window.dataLayer || []; 14 function gtag(){dataLayer.push(arguments);} 15 gtag('js', new Date()); 16 gtag('config', 'GA_TRACKING_ID'); 17 `} 18 </Script> 19 </> 20 ); 21}
When integrating multiple scripts, robust error handling ensures your application remains functional even if a script fails to load. The Script component's onError and onReady props are instrumental in managing these scenarios.
1import Script from 'next/script'; 2 3export default function HomePage() { 4 const handleError = () => { 5 console.error('Script failed to load'); 6 }; 7 8 const handleReady = () => { 9 console.log('Script has finished loading'); 10 }; 11 12 return ( 13 <> 14 <h1>Welcome to My Site</h1> 15 <Script 16 src="https://example.com/faulty-script.js" 17 strategy="afterInteractive" 18 onError={handleError} 19 onReady={handleReady} 20 /> 21 </> 22 ); 23}
Next.js provides the flexibility to use the Script component in specific pages or layouts, ensuring that scripts are only loaded where needed. This practice reduces unnecessary script loading, enhancing performance.
In a Layout Component:
1import Script from 'next/script'; 2 3export default function Layout({ children }) { 4 return ( 5 <> 6 <header>My Site Header</header> 7 <main>{children}</main> 8 <Script src="https://example.com/layout-script.js" strategy="afterInteractive" /> 9 </> 10 ); 11}
In a Specific Page:
1import Script from 'next/script'; 2 3export default function ContactPage() { 4 return ( 5 <> 6 <h1>Contact Us</h1> 7 <Script src="https://example.com/contact-page-script.js" strategy="afterInteractive" /> 8 </> 9 ); 10}
When using custom server components, you can still leverage the Script component to manage script loading. Ensure scripts that need to run on the server-side are correctly placed.
1import { Html, Head, Main, NextScript } from 'next/document'; 2import Script from 'next/script'; 3 4export default function Document() { 5 return ( 6 <Html> 7 <Head> 8 <Script src="https://example.com/server-script.js" strategy="beforeInteractive" /> 9 </Head> 10 <body> 11 <Main /> 12 <NextScript /> 13 </body> 14 </Html> 15 ); 16}
The Script component in Next.js provides a robust and flexible way to manage script loading, enhancing performance and user experience. By leveraging different loading strategies, handling errors gracefully, and optimizing the integration of third-party scripts, you can build efficient and responsive Next.js applications.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.