Skip to content

Commit 87ed943

Browse files
committed
Insert gtm.js script after gtag script
1 parent 4d58d40 commit 87ed943

File tree

1 file changed

+25
-11
lines changed

1 file changed

+25
-11
lines changed

.vitepress/config.ts

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -143,23 +143,37 @@ function getAnalyticsTags({
143143

144144
const tags: HeadConfig[] = [];
145145

146-
// We're migrating from gtag.js to gtm.js, but using both as we verify this change
147-
if (VITE_GTM_ID) {
148-
const js = `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
149-
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
150-
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
151-
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
152-
})(window,document,'script','dataLayer','${VITE_GTM_ID}');`;
153-
tags.push(['script', {}, js]);
154-
}
155-
156146
if (VITE_GTAG_ID) {
157147
const url = `https://www.googletagmanager.com/gtag/js?id=${VITE_GTAG_ID}`;
158148
tags.push(['script', { async: '', src: url }]);
159-
const source = `function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag('js',new Date),gtag('config','${VITE_GTAG_ID}',{anonymize_ip:true})`;
149+
const source = `
150+
window.dataLayer = window.dataLayer || [];
151+
function gtag(){dataLayer.push(arguments)}
152+
gtag('js', new Date);
153+
gtag('config', '${VITE_GTAG_ID}', {anonymize_ip:true});
154+
`;
160155
tags.push(['script', {}, source]);
161156
}
162157

158+
// We're migrating from gtag.js to gtm.js, but using both as we verify this change.
159+
// According to https://support.google.com/tagmanager/answer/6103696 this should be
160+
// inserted after any script declaring a dataLayer.
161+
if (VITE_GTM_ID) {
162+
const js = `
163+
(function(w, d, s, l, i){
164+
w[l] = w[l] || [];
165+
w[l].push({'gtm.start': new Date().getTime(), event: 'gtm.js'});
166+
let f = d.getElementsByTagName(s)[0];
167+
let j = d.createElement(s);
168+
let dl = l != 'dataLayer' ? '&l=' + l : '';
169+
j.async = true;
170+
j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
171+
f.before(j);
172+
})(window, document, 'script', 'dataLayer', '${VITE_GTM_ID}');
173+
`;
174+
tags.push(['script', {}, js]);
175+
}
176+
163177
return tags;
164178
}
165179

0 commit comments

Comments
 (0)