Open In App

Next.js Script Component

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
3 Likes
Like
Report

The Next.js Script component helps you manage when and how scripts are loaded to make your site perform better. It offers three strategies: beforeInteractive for scripts that need to load immediately, afterInteractive for scripts that are needed after the page becomes interactive but aren’t crucial for the initial load, and lazyOnload for scripts that can be loaded during idle times to avoid slowing down the main content. This guide will explain how to use these strategies in your Next.js project to improve page speed and user experience.

These are the following topics that we are going to discuss:

The <script> component

The <script> component in Next.js lets you add custom scripts to your pages in a secure and efficient way. It offers various options to control when and how scripts run, helping to optimize performance. This component is a custom version of the standard HTML <script> tag, providing extra features and better integration with the Next.js framework.

Props

Prop Type Description
src String URL of the external script file to be loaded.
id String Unique identifier for the script.
onLoad Function Callback function to execute after the script has loaded.
onError Function Callback function to execute if there's an error loading the script.
strategy String Specifies the loading strategy for the script.
dangerouslySetInnerHTML Object Allows setting inner HTML content directly. Use with caution.
type String Specifies the MIME type of the script.
async Boolean Indicates that the script should be executed asynchronously.
defer Boolean Indicates that the script should be executed after the document has been parsed
crossOrigin String Indicates the CORS setting for the script request.
integrity String Allows the browser to verify the integrity of the script.
nonce String A cryptographic nonce to allow the script to run under a Content Security Policy.

Required Props

Some props are essential for the proper functioning of the <script> component:

src: URL of the external script file to be loaded.

Optional Props

It accepts a number of additional properties. basically, it provides the

The following props are optional but provide additional control and functionality:

  • strategy
  • beforeInteractive
  • afterInteractive
  • lazyOnload
  • worker
  • onLoad
  • onReady
  • onError

Strategy

The strategy prop specifies the loading strategy for the script. It accepts the following values:

  • Value: It takes the type of strategy that we are going to use
  • src: It takes the source of the loading component

Steps to Create Application (Install Required Modules)

Step 1: Initialize a new Next.js project

npx create-next-app next-js-script-demo
cd next-js-script-demo

Step 2: Install necessary dependencies:

npm install next react react-dom

Folder Structure:

Project STructure

Dependencies

"dependencies": {
"next": "latest",
"react": "latest",
"react-dom": "latest"
}

Before Interactive (beforeInteractive)

Loads the script before the page becomes interactive. Useful for scripts that need to run early.

This approach ensures that the script is loaded and executed before the page becomes interactive. It is useful for critical scripts that need to be available immediately.

JavaScript
//src/components/BeforeInteractiveExample.jsx

import Script from "next/script";

export default function BeforeInteractiveExample() {
    return (
        
            Before Interactive Script Example
                                                
        
    );
}
JavaScript

Output:

Screenshot-2024-07-17-214950-(1)
Output

After Interactive (afterInteractive)

This approach loads and executes the script after the page becomes interactive. It is useful for non-critical scripts that can wait until the page is fully interactive.

Syntax:


src="https://example.com/noncritical.js"
strategy="afterInteractive"
/>

Example : Create a new component AfterInteractiveExample.jsx inside a components directory under in the src directory:

JavaScript
//src/components/AfterInteractiveExample.jsx

import Script from 'next/script';

export default function AfterInteractiveExample() {
    return (
        
            After Interactive Script Example
                                                
        
    );
}
JavaScript

Output:

AfterInteractiveExample_OutPut-(1)
Output

Lazy Onload (lazyOnload)

This approach loads the script lazily during idle time. It is useful for scripts that are not necessary for the initial page load and can be loaded when the browser is idle.

Syntax:

<script
src="https://example.com/lazy.js"
strategy="lazyOnload"
/>

Example: Create a new component LazyOnloadExample.jsx in the Components directory.

JavaScript
//src/components/LazyOnloadExample.jsx

import Script from "next/script";

export default function LazyOnloadExample() {
    return (
        
            Lazy Onload Script Example
            
        
    );
}
JavaScript

Output:

Screenshot-2024-08-02-144447
Output

Example: For demonstration, let's integrate all three script loading strategies into a single page:

JavaScript
//src/components/ScriptExample.jsx

import Script from "next/script";

export default function ScriptExample() {
    return (
        
            Next.js Script Component Example
                                                
                                                
            
        
    );
}
JavaScript

Note: Create a new component ScriptExample.jsx in the Components directory.

Output:

final_OutPut-(1)
Output

Conclusion

The Next.js Script component is crucial for optimizing script loading in web applications. It lets you control the timing and order of script execution to boost performance and enhance user experience. The afterInteractive strategy loads scripts that aren't needed for the initial render but are essential for interactive features, preventing delays in loading the main content. The lazyOnLoad strategy is ideal for non-essential scripts, loading them during idle time to minimize impact on the main thread and further improve performance.


Next Article

Similar Reads