Table of contents
1.
Introduction
2.
How it works
3.
Working with script optimization
3.1.
beforeInteractive
3.2.
afterInteractive
3.3.
lazyOnload
4.
Inline Scripts
5.
onLoad
6.
onError
7.
Frequently Asked Questions
8.
Key Takeaways
Last Updated: Mar 27, 2024

Script Optimization

Author Abhay Trivedi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Many Websites usually have third-party scripts to include different types of functionality such as analytics, ads, widgets, consent management, etc. Some scripts are heavy on loading performance and can drag down the user experience, mainly in render-blocking, which can delay any page content from loading. Developers often struggle to place third-party scripts in an application to ensure optimal loading times.

Here comes the Script optimization, making it easier for developers to place a third-party script anywhere in their application while optimizing its rendering speeds.

How it works

To add a third-party script in your application, run the following command to import the next/script component:

import Script from 'next/script'
You can also try this code with Online Javascript Compiler
Run Code

Working with script optimization

Using next/script and strategy property, you decide when to load your third-party script:

<Script src="https://www.google-analytics.com/analytics.js" strategy="lazyOnload" />
You can also try this code with Online Javascript Compiler
Run Code

 

We can use three different loading strategies:

  • beforeInteractive: Loads before the page is interactive
  • afterInteractive: Loads immediately after the page becomes interactive (default).
  • lazyOnload: Loads during idle time

beforeInteractive

Scripts with the beforeInteractive strategy are injected into the initial HTML from the server and run before self-bundled JavaScript. We should use this strategy for any critical scripts that need to be fetched and completed before the interactive page—for example, Bot detectors & Cookie consent managers.

import Script from 'next/script'

export default function Home() {
 return (
   <>
     <Script src="https://url.com/examplescript.js"
       strategy="beforeInteractive"
     />
   </>
 )
}
You can also try this code with Online Javascript Compiler
Run Code

afterInteractive

Scripts with the afterInteractive strategy are injected client-side and run after Next.js hydrates the page. We should use this strategy for scripts that do not need to load as soon as possible and can be fetched and run immediately after the interactive page—for example, Tag managers & Analytics.

// default afterinteractive strategy will apply when the strategy is not specified.
import Script from 'next/script'

export default function Home() {
 return (
   <>
     <Script src="https://url.com/examplescript.js" />
   </>
 )
}
You can also try this code with Online Javascript Compiler
Run Code

lazyOnload

Script Optimization with the lazyOnload strategy is loaded late after all resources are fetched and during idle time. We should use this strategy for background or low-priority scripts that do not need to load before or immediately after a page becomes interactive—for example, Chat support plugins & Social media widgets.

import Script from 'next/script'

export default function Home() {
 return (
   <>
     <Script src="https://url.com/examplescript.js" strategy="lazyOnload"
     />
   </>
 )
}
You can also try this code with Online Javascript Compiler
Run Code

Inline Scripts

Script component also supports Inline scripts that are not from an external file. We can write by placing the JavaScript within the curly braces like:

<Script id="show-tag" strategy="lazyOnload">
  {`document.getElementById('tag').classList.add('hidden')`}
</Script>
You can also try this code with Online Javascript Compiler
Run Code

Note: We cannot use the beforeInteractive strategy with inline scripts, and we must also define id.

onLoad

Some third-party scripts require running JavaScript code after the script has completed loading to instantiate content or call a function. You can execute code after loading using the onLoad property if your loading strategy is beforeInteractive or afterInteractive.

Syntax:

<Script
   src={https://url.com/examplescript.js}
   strategy="beforeInteractive" // or afterInteractive
   onLoad={() => {
     // After loading successfully, you can load other scripts in sequence
   }}
/>
You can also try this code with Online Javascript Compiler
Run Code

onError

Occasionally it is helpful to catch when a script fails to load. We can handle these errors with the onError property:

import Script from 'next/script'

export default function Home() {
  return (
    <>
      <Script
        id="error-prone"
        src="https://url.com/examplescript.js"
        onError={(e) => {
          console.error('Script has failed to load', e)
        }}
      />
    </>
  )
}
You can also try this code with Online Javascript Compiler
Run Code

Frequently Asked Questions

1. What is Next.js?

Next.js is an open-source development framework made on top of Node.js, allowing React-based web application functionalities such as server-side generating and rendering static websites.

2. What are the benefits of using Next.js?

Next.js comes with numerous features that translate into benefits for business and marketing and the development process. The most meaningful thing that developers love is reusable components. As for business, it cuts the development costs. As for developers, it cuts the development time.

3. what is next/script?

The Next. js Script component (next/script), is an extension of the HTML <script> element. It allows developers to set the loading priority of third-party scripts anywhere in their application without requiring to append directly to next/head, preserving developer time while improving loading performance.

Key Takeaways

This article teaches about Script Optimization and how we use it. We saw why Script Optimization could be beneficial for a developer to learn. Click here to read about Angular Vs. React.

Click here to see other related blogs on Next.js.

Check out our Web development course and blogs on Frontend Web Technologies.

If you are preparing for your DSA interviews then, Coding Ninjas Studio is a one-stop destination. This platform will help you acquire effective coding techniques and overview student interview experience in various product-based companies.


Happy Learning!

Live masterclass