在外部js文件中包含谷歌分析

to94eoyn  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(328)

我想知道如何将下面的google analytics代码添加到所有页面都在访问的外部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.

任何帮助都将不胜感激,因为我在网上其他地方找不到答案。

xhv8bpkk

xhv8bpkk1#

尝试将此添加到您的 /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)

相关问题