javascript - 如果设置了 cookie,则嵌入谷歌分析
问题描述
我想执行这样的事情:
if (document.cookie.indexOf('cookie') > -1 ) {
<script>...
<script>
window.dataLayer = window.dataLayer || [];
etc.
}
我在其他地方读到 document.write 是一个不好的方法。
谢谢。
解决方案
反方向包起来。使用<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()
推荐阅读
- python - 如何在继承自抽象基类的类中定义方法
- tcp - 当我们想使用 Javascript 通过 WebSocket 进行通信时,套接字如何将端口从 HTTP 80 更改为另一个端口?
- ruby-on-rails - Rails 4.2 Postgres 9.4.4 statement_timeout 不起作用
- sql-server - 使用 SQL Sserver 2008 重命名表中的列
- php - sort array using array_unique from external XML (CDATA)
- db2 - IBM Bluemix Db2 on Cloud“错误 401:SRVE0295E:报告的错误:401”
- swift - 有没有更简单的方法以编程方式查看 UIImageView ?
- reactjs - 将函数传递给组件但接收未定义
- html - 使用 XPath 选择具有最高 z-index 值的项目
- leaflet - RPG地图问题