Script Optimization
What does the Script Component do?
The script component makes it possible for developers to set a loading priority on third-party scripts. This saves developer time and improves loading performance.
With next/script
you can define the strategy
property and Next.js will optimize loading for the script.
Ways to define the strategy
property
beforeInteractive
: Critical scripts that need to be fetched and executed before the page is interactive.These scripts will get injected into the initial HTML from the server and run before self-bundled JavaScript is executed.
Good place to put:
Bot detection
Consent management
afterInteractive
: Default SettingThis is for scripts that can fetch and execute after the page is interactive.
Injected on client-side and will run after hydration.
Good place to put:
Tag managers
Analytics
lazyOnload
: Scripts can wait to load during idle time.Good place to put:
Chat support
Social media widgets
How to use the script optimization
You have to start by defining a
script
tag inside of theHead
of your Next.js page.After that, you can use
next/script
in the body of your Next.js page.