Reputation: 51
We are using Next.js, and pagespeed score got worse after gtm and fb pixel, google script for sign.
for GTM, tried
https://www.npmjs.com/package/react-gtm-module initializing in _app.js
also tried using script tag in _app.js
<script
dangerouslySetInnerHTML={{
__html: `
(function(w,d,s,l,i)
{w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID}');
`,
}}
/>
For Facebook Pixel: tried https://www.npmjs.com/package/react-facebook-pixel
<script
dangerouslySetInnerHTML={{
__html: `
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', ${FB_PIXEL_ID});
`,
}}
/>
tried adding defer also no effect.
without tags getting score around 60,
Upvotes: 0
Views: 1092
Reputation: 5840
It's hilarious that Google and Facebook recommend that we put their inline, blocking code in the head or as the first item in the body so they can start gathering data for themselves, but then Google dings us for blocking. If you want to defer these, there are two primary ways:
Script
component to help load/lazy load/defer external scripts.Document
component and put your external scripts after the NextScript
component, before the closing </body>
tag.These solutions would move those codes to later in the loading process so they're non-blocking, which should help with your loading times. The tradeoff is that they won't initialize until after the page is loaded, so you'd have to decide which is more important - faster loading time and better user experience for your customers, or a smidge of more analytics on users who leave the site before it fully loads at the expense of a little longer loading time.
Upvotes: 3