Created
November 23, 2022 14:00
-
-
Save Slakinov/6db5905de43995323065387d0f67fcda to your computer and use it in GitHub Desktop.
Instant Google Analytics for SvelteKit, add to +layout.svelte
This file contains 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
<script> | |
import { page } from '$app/stores'; | |
import { browser } from '$app/environment'; | |
import { onMount } from 'svelte'; | |
export let id; | |
onMount(() => { | |
window.dataLayer = window.dataLayer || []; | |
window.gtag = function() { window.dataLayer.push(arguments) } | |
window.gtag('js', new Date()); | |
window.gtag('config', id); | |
// console.log('GA init: '+id); | |
record($page.url.pathname); | |
}); | |
$: { | |
if(browser) { | |
if (window.gtag != undefined) { | |
record($page.url.pathname); | |
} | |
} | |
} | |
function record(url) { | |
window.gtag('config', id, { 'page_path': url}); | |
// console.log('GA: '+url); | |
} | |
</script> | |
<svelte:head> | |
<script async src="https://www.googletagmanager.com/gtag/js?id={id}"></script> | |
</svelte:head> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment