#Using 3 party scripts in Nextjs

1 messages · Page 1 of 1 (latest)

supple hemlockBOT
#

Hi @smoky venture. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To load third-party scripts in Next.js for better performance, you can use the next/script component and leverage its strategy property to control the loading behavior. Based on the provided code and the knowledge sources, here is how you can optimize the loading of third-party scripts:

  1. Use the strategy property: The strategy property allows you to control when the script should be loaded. The available options are:

    • beforeInteractive: Load the script before any Next.js code and before any page hydration occurs.
    • afterInteractive: (default) Load the script early but after some hydration on the page occurs.
    • lazyOnload: Load the script later during browser idle time.
    • worker: (experimental) Load the script in a web worker.
  2. Example Code: In your provided code, you are already using the afterInteractive strategy for loading Google Analytics scripts, which is a good practice for performance. Here is the code snippet with the next/script component:

import './globals.css';
import { Nunito } from 'next/font/google';
import Navbar from './components/navbar/Navbar';
import ToasterProvider from './providers/ToasterProvider';
import { ModalProvider } from './contexts/ModalContext';
import { UserProvider } from './contexts/UserContext';
import Script from 'next/script';
import Footer from './components/footer/Footer';
import dynamic from 'next/dynamic';

const font = Nunito({ subsets: ['latin'] });

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const currentUser = await getCurrentUser();
#

return (
<html lang="en">
<Script
async
src={<https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}}>
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{ window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}'); }
</Script>
<body className={${font.className} flex flex-col min-h-screen}>
<ToasterProvider />
<ModalProvider>
<UserProvider username={currentUser?.username || ''}>
<Navbar currentUser={currentUser} />
<div className="pt-0 sm:pt-8 flex-grow">{children}</div>
<Footer />
</UserProvider>
</ModalProvider>
</body>
</html>
);
}


3. **Recommendation**: As per the knowledge sources, it is recommended to include third-party scripts in specific pages or layouts to minimize any unnecessary impact on performance. This ensures that scripts are only loaded when needed and do not affect the overall performance of your application.

For more details, you can refer to the **Next.js Script Optimization documentation** (<https://nextjs.org/docs/app/building-your-application/optimizing/scripts#strategy>).

By following these practices, you can ensure that your third-party scripts are loaded efficiently, improving the performance of your Next.js application.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@smoky venture kapa.ai is still learning and improving, please let us know how it did by reacting below

smoky venture
#

@supple hemlock So are you saying I should move that Scripts from RootLayout to somewhere else?

supple hemlockBOT
#

Let me check the knowledge base for you. One moment! :books:

#

No, you do not necessarily need to move the Script components from RootLayout if they are intended to be global scripts that should be loaded on every page. However, you should ensure that they are correctly placed and use the appropriate strategy for optimal performance.

Based on the provided code and the knowledge sources, here is a summary of best practices for loading third-party scripts in Next.js:

  1. Global Scripts: If the scripts are required globally (e.g., Google Analytics), it is appropriate to place them in the RootLayout component. This ensures that they are loaded on every page.

  2. Use Appropriate Strategy: Use the strategy property of the next/script component to control when the script should be loaded. For example, afterInteractive is a good choice for scripts that should be loaded after the initial page hydration.

Here is your provided code with the Script components correctly placed in the RootLayout:

import './globals.css';
import { Nunito } from 'next/font/google';
import Navbar from './components/navbar/Navbar';
import ToasterProvider from './providers/ToasterProvider';
import { ModalProvider } from './contexts/ModalContext';
import { UserProvider } from './contexts/UserContext';
import Script from 'next/script';
import Footer from './components/footer/Footer';
import dynamic from 'next/dynamic';

const font = Nunito({ subsets: ['latin'] });

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const currentUser = await getCurrentUser();
#

return (
<html lang="en">
<Script
async
src={<https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}}>
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{ window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}'); }
</Script>
<body className={${font.className} flex flex-col min-h-screen}>
<ToasterProvider />
<ModalProvider>
<UserProvider username={currentUser?.username || ''}>
<Navbar currentUser={currentUser} />
<div className="pt-0 sm:pt-8 flex-grow">{children}</div>
<Footer />
</UserProvider>
</ModalProvider>
</body>
</html>
);
}


### Key Points:
- **Global Placement**: Keep global scripts in the `RootLayout` if they need to be loaded on every page.
- **Strategy Usage**: Use the `strategy` property to control the loading behavior of the scripts. `afterInteractive` is suitable for scripts like Google Analytics that should load after the initial page hydration.

For more details, you can refer to the **Next.js Script Optimization documentation** (<https://nextjs.org/docs/app/building-your-application/optimizing/scripts#strategy>).

By following these practices, you can ensure that your third-party scripts are loaded efficiently, improving the performance of your Next.js application.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------