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

时间:2018-07-03 12:24:07

标签: javascript cookies google-analytics

当用户不想获取Cookie时,我正在尝试使用JavaScript阻止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>

1 个答案:

答案 0 :(得分:3)

尝试这样的事情:

    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);
}

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