-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
22 lines (20 loc) · 921 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const cheerio = require('cheerio')
function generateGTagSnippet(id, minified) {
return minified ? `<script async src="https://www.googletagmanager.com/gtag/js?id=${id}"></script><script>window.dataLayer=window.dataLayer||[],window.gtag=function(){dataLayer.push(arguments)},gtag("js",new Date),gtag("config","${id}")</script>`
: `
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=${id}"></script>
<script>
window.dataLayer = window.dataLayer || [];
window.gtag = function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${id}');
</script>
`
}
module.exports = function injectGTag(html, trackingID, minify) {
const $ = cheerio.load(html)
$('head').prepend(generateGTagSnippet(trackingID, minify))
// If input html is empty, we simply output the content of <head>
return html ? $.html() : $('head').html()
}