首页 > 解决方案 > 如果设置了 cookie,则嵌入谷歌分析

问题描述

我想执行这样的事情:

if (document.cookie.indexOf('cookie') > -1 ) {
  <script>...
  <script>
   window.dataLayer = window.dataLayer || [];
   etc.
}

我在其他地方读到 document.write 是一个不好的方法。

谢谢。

标签: javascript

解决方案


反方向包起来。使用<script>标签,然后if在里面:

<script>
    if (document.cookie.indexOf('cookie') > -1 ) {
        window.dataLayer = window.dataLayer || [];
        /* ... */
    }
</script>

然后,如果不存在 cookie,脚本将不会启动。


如果您需要一些自定义标签,请使用此代码(在 jQuery 中,但您会明白的)

var head = $('head'); // Select <head>, or any other element that will wrap your script
var scriptTag = $('<script>', {async: 'async', src: 'http://google.com/...', /*... */}); // Create new element in head

head.prepend(scriptTag); // Put your new element to the end of <head>

但你真的需要吗?尝试使用jQuery.getScript()


推荐阅读