Reputation: 1184
I want to add my Google Analytics Tracking ID
- UA-XXXXXXXXX-X
to my svelte app.
I found two ways of doing it.
First using Install the global site tag
here
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
</script>
I think, I have to insert the above code in app.svelte
. Am I right?
Second, using @beyonk/svelte-google-analytics
Installing package using
npm i --save-dev @beyonk/svelte-google-analytics
import { GoogleAnalytics } from '@beyonk/svelte-google-analytics'
<GoogleAnalytics properties={[ 'google property id A', ...'google property id X' ]} />
So where here am I suppose to add tracking ID
? This is how it is mentioned in svelte documentation here
The first
or the second
method to use? This is confusing
Upvotes: 1
Views: 3822
Reputation: 1205
The correct way is to add the google code to the app.svelte like this : 1- inside svelte:head </svelte:head> insert the code with script.
<svelte:head>
<!-- Google Tag Manager -->
<script>
(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','000');
</script>
<!-- End Google Tag Manager -->
</svelte:head>
and after the beginning of the body tag or the main tag insert the nonscript code :
<main>
<!-- Google Tag Manager (noscript) -->
<noscript>
<iframe title="gtm" src="https://www.googletagmanager.com/ns.html?id=0000"
height="0" width="0" style="display:none;visibility:hidden">
</iframe>
</noscript>
<!-- End Google Tag Manager (noscript) -->
</main>
reload your app - which means run npm run build - and upload your files to your server. Check the head tag, the code script tag for google tag manager will be there in the head and nonscript code will be in the body. You're done.
Upvotes: 2
Reputation: 61
You can add the global site tag within public/index.html
. All of your Svelte will be injected into this file, so it will handle all of your pages.
EDIT: SvelteKit 1.0 has this base HTML file as app.html
in in the root directory, but for whatever flavor of Svelte you're using, just make sure to add it to the HTML file that is hydrated with Svelte.
Upvotes: 6
Reputation: 820
To insert multiline html into .svelte
file:
{@html `<!-- google tag analytics goes here -->
<!-- ... -->
<!-- / -->`}
or you can insert code into app.html
Upvotes: 1