Nextjs

The Script component in Next.js?

The nextjs Script component helps to optimize and improve loading performance in your web app. This article is part of my nextjs #SeriesPart11.

Rajdeep Singh
FrontEnd web

--

Next.js provides lots of functionality for the developer without any code. Nextjs Script component is one of them. In nextjs Script component help to add third-party javascript like google Adsense, google analytics, stripe, tailwind CSS, and many more.

Nextjs automatically optimize your app with the nextjs script component. You do not worry about configuration and other stuff.

Script component in Next.js.

Demo

Play with code online. Plz, check the _app.js file.

How to use the script component in nextjs?

You use Script components in pages, custom components, and custom _app.js file.

Firstly, import the script component in next.js.

import Script from 'next/script'

Now you use the script component in next whatever place. if you use javascript SDK or CDN to add-in _app.js

<Script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" />

For example, I add bootstrap 5 with my website's head and Script component. So I will show you a real-life scenario. how to use script tag in next.js?

import Script from "next/script";
import Head from "next/head";
export default function MyApp({ Component, pageProps }) {
return (
<>
<Head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossOrigin="anonymous" />
</Head>
<Script
id="bootstrap-cdn"

src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" />
<Component {...pageProps} />
</>
);
}

Copy and paste your custom app and start bootstrap in nextjs with CDN.

Additional property

Nextjs provide Additional property in the Script component. You additional property to enhance web speed and stability in nextjs.

  1. id
  2. strategy
  3. dangerouslySetInnerHTML
  4. Inline scripts
  5. onLoad
  6. onError
  7. Additional attributes
  8. Full Example

id

According to nextjs id attribute help to track and optimize the third-party script or custom script. A good approach in nextjs is you always define the id attribute in the script component. You use the id attribute to apply CSS easily.

<Script  id="bootstrap-cdn"     src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"  strategy='lazyOnload' />

strategy

In nextjs strategy, property help defines strategies and how to load nextjs third-party script. nextjs provide three properties.

strategy property can use three different loading strategies:

  • beforeInteractive: Load before the page is interactive
  • afterInteractive: (default): Load immediately after the page becomes interactive
  • lazyOnload: Load during idle time
<Script  id="bootstrap-cdn"     src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"  strategy='lazyOnload' />

dangerouslySetInnerHTML

In script component you also add dangerouslySetInnerHTML tag to add inner HTML. This property is mostly used in reactjs like or similar frameworks. Nextjs team recommended, you to use the afterInteractive property with dangerouslySetInnerHTML.

<Script
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer', 'GTM-XXXXXX');
`,
}}

/>

Inline scripts

In the script component, allow you to add inline javascript in nextjs. You write javascript within the closing and opening tag. Inline javascript and dangerouslySetInnerHTML work similar. in dangerouslySetInnerHTML properly I told you in previous.

<Script id="show-banner" strategy="lazyOnload">
{`document.getElementById('banner').classList.remove('hidden')`}
</Script>

Suppose you add your own javaScript choice one of them, inline script or dangerouslySetInnerHTML. You do not use inline script or dangerouslySetInnerHTML both in your project.

onLoad

In most cases in the javascript world, first, load third-party javascript in the browser and then start interaction with dom. onLoad provides similar is similar functionality.

The nextjs script component onLoad property takes a function as a value. You pass arrow or regular function it bases on the requirement.

import Script from 'next/script'

export default function Home() {
return (
<>
<Script
id="onload-id"
src="https://cdn.example.com/script.js"
onLoad={() => {
// ... code here
}}

/>
</>
)
}

onError

onError is a similar property to onLoad. But onLord function runs after the third part javaScript load in the browser, and other hand onError property runs when the script component faces any error related to the third-party script. Maybe third party src path is changed like that.

Use of onError property, you also handle third-party errors in your production Nextjs app.

import Script from 'next/script'

export default function Home() {
return (
<>
<Script
id="onerror-id"
src="https://cdn.example.com/script.js"
onError={(e) => {
console.log("error: ",e)
}}

/>
</>
)
}

Additional attributes

Nextjs script component optimizes your script with additional HTML attributes. The HTML script tag comes with lots of attributes and properties. nextjs script component based on HTML script tag.

nextjs automatically apply those attributes and properties according to their requirement. You do not add another attribute in the script component.

Full Example

import Script from 'next/script'

export default function Home() {
return (
<>
<Script
id="script-id"
src="https://cdn.example.com/script.js"
dangerouslySetInnerHTML={{
__html: code here
}}
onLoad={ ()=> { console.log('code here')}}
onError={(e) => {
console.log("error: ",e)
}}

/>
</>
)
}

Previous Articles

https://medium.com/nextjs/install-tailwind-css-in-next-js-37a56bd64fa7

https://medium.com/nextjs/how-to-use-middleware-in-nextjs-2013f6289f5

Conclusion

Nextjs Script component is very used full when using the third-party script in the nextjs app. Script components help to provide lots of functionality like onLoad and onError. I recommended you always use the id attribute with the Script component because the nextjs team recommends it.

If you have any queries or find my help, don't hesitate to contact me at officialrajdeepsingh@gmail.com. Are you migrate react to nextjs, then you also contact me.

Feel free to like and share my article with others if you like my writing. You also tag on Twitter official_R_deep.

Read More content at Nextjs. Sign up for a free newsletter and join the nextjs community on medium.

--

--

Rajdeep Singh
FrontEnd web

Follow me if you learn more about JavaScript | TypeScript | React.js | Next.js | Linux | NixOS | https://linktr.ee/officialrajdeepsingh