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
//src/app/page.tsx
import BeforeInteractiveExample from '../components/BeforeInteractiveExample'
export default function Home() {
return (
);
}
Output:
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
//src/app/page.tsx
import AfterInteractiveExample from '../components/AfterInteractiveExample'
export default function Home() {
return (
);
}
Output:
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
//src/app/page.tsx
import LazyOnloadExample from '../components/LazyOnloadExample';
export default function Home() {
return (
);
}
Output:
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
//src/app/page.tsx
import ScriptExample from '../components/ScriptExample';
export default function Home() {
return (
);
}
Note: Create a new component ScriptExample.jsx in the Components directory.
Output:
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.
Similar Reads
Next.js Components : <Script>
The <Script> component in Next.js allows you to load third-party scripts efficiently, optimizing performance and enhancing control over when and how scripts are executed within your application.In this post, we will learn about the Next.js Script component.Table of ContentScript ComponentsSynt
6 min read
Remix Components: Scripts
The Scripts component is extremely important for putting JavaScript on a web page in Remix. This guarantees that your JavaScript files and inline scripts are put at appropriate places in the document, as a general rule in the elements of your HTML code. As such, Remix controls when and where to put
4 min read
Next.js Components
Next.js components are integral to building modular and efficient applications, offering tools like Image, Link, Script, and Font to handle media, navigation, scripts, and typography effectively. These components enhance performance and streamline development in Next.js.Table of ContentWhat is a Com
4 min read
Server Components in Next.js
Server Components in Next.js offer a way to build components that are rendered on the server rather than on the client. This feature enhances performance by reducing the amount of JavaScript sent to the browser and allows for faster initial page loads. In this post, we will explore the Server Compon
4 min read
Next.js Link Component
The Link component in Next.js is used to navigate between pages in a Next.js application. It enables client-side navigation, which provides a smoother user experience by avoiding full-page reloads. This component is crucial for building Single Page Applications with Next.js, as it allows for efficie
2 min read
Next JS Layout Component
Next JS Layout components are commonly used to structure the overall layout of a website or web application. They provide a convenient way to maintain consistent header, footer, and navigation elements across multiple pages. Let's see how you can create and use a Layout component in Next.js. Prerequ
3 min read
NextJS Image Component
The image component in Next.js is powerful. It will assist you in optimizing and serving images efficiently. It has responsive loading and lazy loading built in, which can greatly boost the performance and user experience of your application by reducing the loading times of a page. This automaticall
8 min read
React Components
In React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
Next.js Client Components
Next.js, a popular React framework, has seen significant growth in recent years due to its robust features for building modern web applications. One of the key concepts introduced in Next.js is the distinction between Server and Client Components. In this article, we'll focus on Client Components an
4 min read
Next.js TypeScript
NextJS is a powerful and popular JavaScript framework that is used for building server-rendered React applications. . It provides a development environment with built-in support for TypeScript, as well as a set of features that make it easy to build and deploy web applications. It was developed by Z
4 min read