I am using Next JS on a project and I am going through some optimizations using Google's Page Speed Insights tool. One of the main negative contributers to my sites performance is 3rd party scripts mainly being Google Tag script (which also loads my Google Analytics) and the Google maps API script. So far I have tried several things to offset the loading of these two libraries but I still get the following messages from the tool:
Remove unused JavaScript
https://maps.googleapis.com/maps/api/js?key=asdafsafasafasfasf&libraries=places&language=en®ion=US
(maps.googleapis.com)
https://www.googletagmanager.com/gtag/js?id=UA-123123-2
(www.googletagmanager.com)
I need to have these scripts loaded everywhere on the site so I tried to delay the loading of the scripts until the everything else on the page was finished loading. Here is what I initially had:
_document.js
import Document, { Head, Main, NextScript, Html } from "next/document";
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html lang="en">
<Head>
<script
defer
src={`https://www.googletagmanager.com/gtag/js?id=UA-123123-2`}
/>
<script
defer
src="https://maps.googleapis.com/maps/api/js?key=asdafsafasafasfasf&libraries=places&language=en®ion=US"
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-123123-2');
`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
As you can see I just load in the scripts with the defer prop like you normally would. With this method google page speed insights still give me the same message however. I then tried a different approach using an experimental component in Next JS called ScriptLoader which aims to allow people to defer scripts. Here is a link to that component:
https://github.com/vercel/next.js/discussions/18172
Here is my implementation of it:
_app.js
import App from "next/app";
import ScriptLoader from "next/dist/client/experimental-script.js";
export default class NextApp extends App {
render() {
return (<>
<ScriptLoader
strategy="defer"
src="https://www.googletagmanager.com/gtag/js?id=UA-123123-2"
/>
<ScriptLoader
strategy="defer"
src="https://maps.googleapis.com/maps/api/js?key=asdafsafasafasfasf&libraries=places&language=en®ion=US"
/>
</>)
}
}
It still however gives me the same error message. I am not sure what to try now! Has anyone else come across this issue and found a workaround?
Thanks