Skip to content

Commit e694b89

Browse files
committed
Don’t explicitly load gtag/js if we’re loading gtm.js, only define dataLayer
1 parent 87ed943 commit e694b89

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed

.vitepress/config.ts

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -144,34 +144,36 @@ function getAnalyticsTags({
144144
const tags: HeadConfig[] = [];
145145

146146
if (VITE_GTAG_ID) {
147-
const url = `https://www.googletagmanager.com/gtag/js?id=${VITE_GTAG_ID}`;
148-
tags.push(['script', { async: '', src: url }]);
149147
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-
`;
148+
window.dataLayer = window.dataLayer || [];
149+
function gtag(){ dataLayer.push(arguments) }
150+
gtag('js', new Date);
151+
gtag('config', '${VITE_GTAG_ID}', { anonymize_ip: true });
152+
`;
155153
tags.push(['script', {}, source]);
154+
if (!VITE_GTM_ID) {
155+
const url = `https://www.googletagmanager.com/gtag/js?id=${VITE_GTAG_ID}`;
156+
tags.push(['script', { async: '', src: url }]);
157+
}
156158
}
157159

158160
// We're migrating from gtag.js to gtm.js, but using both as we verify this change.
159161
// According to https://support.google.com/tagmanager/answer/6103696 this should be
160162
// inserted after any script declaring a dataLayer.
161163
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]);
164+
const source = `
165+
(function(w, d, s, l, i){
166+
w[l] = w[l] || [];
167+
w[l].push({'gtm.start': new Date().getTime(), event: 'gtm.js'});
168+
let f = d.getElementsByTagName(s)[0];
169+
let j = d.createElement(s);
170+
let dl = l != 'dataLayer' ? '&l=' + l : '';
171+
j.async = true;
172+
j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
173+
f.before(j);
174+
})(window, document, 'script', 'dataLayer', '${VITE_GTM_ID}');
175+
`;
176+
tags.push(['script', {}, source]);
175177
}
176178

177179
return tags;

0 commit comments

Comments
 (0)