Sometime your app requires third-party JavaScript to work, such as when you're loading Google ads, or some other third-party services. How you are loading the scripts can make a huge difference in terms of the overall performance of the app.
Next.js recommends using the built-in <Script>
component when dealing with third-party scripts.
1import Script from "next/script";
2
3export default function Page() {
4 return <Script src="https://example.com/script.js" />;
5}
Loading strategy
The <Script>
component allows you to define a strategy
prop, which determines how you want the script to be loaded.
1import Script from "next/script";
2
3export default function Page() {
4 return (
5 <div>
6 <p>Lorem ipsum dolor . . .</p>
7 <Script
8 src="https://example.com/script.js"
9 strategy="beforeInteractive"
10 />
11 </div>
12 );
13}
The strategy
prop accepts the following options:
beforeInteractive
: The script will be placed in the<head>
section, and will be loaded before the rest of the page.afterInteractive
: This is the default option. The script will be placed right before the closing</body>
tag, and will be loaded right after the page finishes hydrating.lazyOnload
: The script will be loaded after the page finishes loading, when the browser is idle.
Inline scripts
This is rarely used, but the <Script>
component allows you to add inline scripts as well:
1import Script from "next/script";
2
3export default function Page() {
4 return (
5 <div>
6 <div id="banner" className="hidden">
7 Lorem ipsum dolor . . .
8 </div>
9 <Script id="showBanner">
10 {`document.getElementById('banner').classList.remove('hidden')`}
11 </Script>
12 </div>
13 );
14}
When adding inline scripts, the <Script>
component must have an id
, so that Next.js can track and optimize them. The actual script should be placed inside curly braces.
Or you can use the dangerouslySetInnerHTML
prop:
1import Script from "next/script";
2
3export default function Page() {
4 return (
5 <div>
6 <div id="banner" className="hidden">
7 Lorem ipsum dolor . . .
8 </div>
9 <Script
10 id="showBanner"
11 dangerouslySetInnerHTML={{
12 __html: `document.getElementById('banner').classList.remove('hidden')`,
13 }}
14 />
15 </div>
16 );
17}
In practice, adding inline scripts is not recommended. As a fullstack JavaScript application, Next.js should be in charge of the logic, both in the frontend and backend.
For instance, the above example changes the visibility of #banner
, which is something we could do with Next.js instead of plain JavaScript.