如何在JavaScript中动态加载gtag.js(Google Analytics)?

4

我正在尝试使用JavaScript在用户不想获得Cookie时屏蔽Google Analytics。

if (want_cookie != "no"){
   /* load google analytics script */
 }

但是我没有找到如何在JavaScript中加载这个脚本...
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-XXXXXX');
</script>
2个回答

9
尝试使用以下方法:

尝试使用以下方法:

    if (want_cookie != "no"){
        var newScript = document.createElement("script");
            newScript.type = "text/javascript";
            newScript.setAttribute("async", "true");
            newScript.setAttribute("src", "https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX");
            document.documentElement.firstChild.appendChild(newScript);
}

所以我的做法是,在检查用户是否同意接受cookies后,动态创建脚本元素,并将其附加到页面上。

2
这似乎是替换第一个<script>,但第二个呢? - David Dahan
请注意,document.documentElement.firstChild并不一定指的是<head>元素! - undefined

0
在接受的答案基础上进行改进,我是这样实现的:
HTML:
<button id="declineButton">Decline</button>
<button id="acceptButton">Accept</button>

JS用于下降:
declineButton.addEventListener("click", () => {
  window["ga-disable-G-XXXX"] = true; // replace G-XXXX with your id
});

接受JS:

acceptButton.addEventListener("click", () => {
  window["ga-disable-G-XXXX"] = false; // replace G-XXXX with your id
  appendScriptToHead();
  executeGoogleAnalyticsScript();
});

function appendScriptToHead() {
  const script = document.createElement("script");
  script.type = "text/javascript";
  script.async = true;
  script.src = "https://www.googletagmanager.com/gtag/js?id=G-XXXX"; // replace G-XXXX with your ID
  document.head.appendChild(script);
}

function executeGoogleAnalyticsScript() {
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
  gtag("js", new Date());
  gtag("config", "G-XXXX"); // replace G-XXXX with your id
}

注意: 根据文档,我们必须确保在执行gtag()之前禁用(设置窗口属性)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接