Last active
May 10, 2023 14:15
-
-
Save martinratinaud/0dad877a9b8f62b27c18d601dc8f0051 to your computer and use it in GitHub Desktop.
Delay display of a component. Useful for scripts that male pageSpeed insights fail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const NEXT_PUBLIC_GTM_ID = process.env.NEXT_PUBLIC_GTM_ID; | |
const NEXT_PUBLIC_HOTJAR_ID = process.env.NEXT_PUBLIC_HOTJAR_ID; | |
import React from 'react'; | |
import Script from 'next/script'; | |
import Delayed from 'modules/Common/components/Delayed'; | |
export default function HeadTag() { | |
return ( | |
<> | |
{NEXT_PUBLIC_GTM_ID && ( | |
<> | |
{/* Global Site Tag (gtag.js) - Google Analytics */} | |
<script async src={`https://www.googletagmanager.com/gtag/js?id=${NEXT_PUBLIC_GTM_ID}`} /> | |
<script | |
dangerouslySetInnerHTML={{ | |
__html: ` | |
window.dataLayer = window.dataLayer || []; | |
function gtag(){window.dataLayer.push(arguments);} | |
gtag('js', new Date()); | |
gtag('config', '${NEXT_PUBLIC_GTM_ID}', { | |
page_path: window.location.pathname, | |
}); | |
`, | |
}} | |
/> | |
</> | |
)} | |
{NEXT_PUBLIC_HOTJAR_ID && ( | |
<Delayed timeout={3000}> | |
{/* Hotjar Tracking Code for https://stakingcrypto.io */} | |
<script | |
dangerouslySetInnerHTML={{ | |
__html: ` | |
(function(h,o,t,j,a,r){ | |
h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)}; | |
h._hjSettings={hjid:${NEXT_PUBLIC_HOTJAR_ID},hjsv:6}; | |
a=o.getElementsByTagName('head')[0]; | |
r=o.createElement('script');r.async=1; | |
r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv; | |
a.appendChild(r); | |
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');`, | |
}} | |
/> | |
</Delayed> | |
)} | |
</> | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect, ReactNode } from 'react'; | |
interface DelayedProps { | |
timeout: number; | |
children: ReactNode; | |
} | |
const Delayed: React.FC<DelayedProps> = ({ timeout, children }) => { | |
const [shouldRender, setShouldRender] = useState(false); | |
useEffect(() => { | |
const timer = setTimeout(() => { | |
setShouldRender(true); | |
}, timeout); | |
return () => { | |
clearTimeout(timer); | |
}; | |
}, [timeout]); | |
return shouldRender ? <>{children}</> : null; | |
}; | |
export default Delayed; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment