Fix google analytics loading

This commit is contained in:
Hazem Krimi
2022-02-12 18:18:51 +01:00
parent 56cbb0008d
commit b6d7feccc1
2 changed files with 40 additions and 25 deletions
-24
View File
@@ -15,8 +15,6 @@ import Footer from '../components/Footer';
import NProgress from 'nprogress'; import NProgress from 'nprogress';
import 'nprogress/nprogress.css'; import 'nprogress/nprogress.css';
import { GOOGLE_ANALYTICS_KEY } from '../utils/gtag';
NProgress.configure({ showSpinner: false }); NProgress.configure({ showSpinner: false });
const App = ({ Component, pageProps }: AppProps) => { const App = ({ Component, pageProps }: AppProps) => {
@@ -38,28 +36,6 @@ const App = ({ Component, pageProps }: AppProps) => {
return ( return (
<> <>
<Script
strategy='afterInteractive'
src={`https://www.googletagmanager.com/gtag/js?id=${GOOGLE_ANALYTICS_KEY}`}
/>
<Script
id='analytics-init'
strategy='afterInteractive'
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', ${GOOGLE_ANALYTICS_KEY}, {
page_path: window.location.pathname,
});
`
}}
/>
<Script <Script
id='styles-init' id='styles-init'
strategy='afterInteractive' strategy='afterInteractive'
+40 -1
View File
@@ -1,6 +1,10 @@
import Document, { DocumentContext } from 'next/document'; import Document, { DocumentContext, Html, Head, Main, NextScript } from 'next/document';
import Script from 'next/script';
import { ServerStyleSheet } from 'styled-components'; import { ServerStyleSheet } from 'styled-components';
import { GOOGLE_ANALYTICS_KEY } from '../utils/gtag';
class Doc extends Document { class Doc extends Document {
static async getInitialProps(ctx: DocumentContext) { static async getInitialProps(ctx: DocumentContext) {
const sheet = new ServerStyleSheet(); const sheet = new ServerStyleSheet();
@@ -26,6 +30,41 @@ class Doc extends Document {
sheet.seal(); sheet.seal();
} }
} }
render() {
return (
<Html>
<Head>
<Script
strategy='afterInteractive'
src={`https://www.googletagmanager.com/gtag/js?id=${GOOGLE_ANALYTICS_KEY}`}
/>
<Script
id='google-analytics'
strategy='afterInteractive'
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', ${GOOGLE_ANALYTICS_KEY}, {
page_path: window.location.pathname,
});
`
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
} }
export default Doc; export default Doc;