在外部 JS 文件中包含 google 分析

Include google analytics in external JS file

我想知道如何获取下面的 Google 分析代码并将其添加到所有页面都在访问的外部 JS 文件中。

现在我所有 html 文件中的代码:

<script async src="https://www.googletagmanager.com/gtag/js?id=XXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'XXXXXXXXXX');
</script> 

我想要的样子:

HTML:

<head>
<script src="/js/google.js"></script>
</head>

google.js:

##Some code that does the same as the code the above. I tried adding the exact snippet, but I don't think it works because of the <script> tags, and I don't know how to remove them since one has an "SRC" attribute.

任何帮助将不胜感激,因为我无法在网络上的其他地方找到这方面的答案。

尝试将此添加到您的 /js/google.js 文件中:


let ga_id = "XXXXXXXX";
let ga_script = document.createElement('SCRIPT');

ga_script.type = 'text/javascript';
ga_script.src = `https://www.googletagmanager.com/gtag/js?id=${ga_id}`;
let script2 = document.createElement('SCRIPT');

script2.type = 'text/javascript';

script2.text = `
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '${ga_id}');`;
  
  document.body.appendChild(ga_script)
  document.body.appendChild(script2)