我的html文件的javascript部分如下所示:
<script async src="myscript.js"></script>
<script async src="//www.googletagmanager.com/gtag/js?id=UA-XXXXXX-X"></script>
<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config','UA-XXXXXX-X');</script>我不是真的javascript专家。所以,我不太明白最后一个脚本在做什么。我想知道是否可以将这些代码复制并粘贴到我的myscript.js中以节省几个字节?
困扰我的是我的脚本的“异步”属性。是否必须在页面开头执行google分析脚本的这一部分?
我读过很多关于这个问题的问题和答案,但没有一个能让我理解清楚。其中大部分是关于以前的分析脚本,而不是这个。
发布于 2018-05-05 23:40:48
// Checks if window.dataLayer already defined. If defined, use that array else creates an empty array.
window.dataLayer=window.dataLayer||[];
//This functions add elements to the above defined array. This array is used by the google analytics script defined at the top.
//arguments is a javascript keyword to fetch all arguments passed to a function as an array.
function gtag(){
dataLayer.push(arguments);
}
//gtag called with arguments ['js', <current date>]
gtag('js',new Date());
//gtag called with arguments ['config', <token>]
gtag('config','UA-XXXXXX-X');最终结果将是:
datalayer=[
['js', <current date>],
['config', <token>]
]您的数据层应该在gtag脚本调用之前定义,否则可能无法工作。这个链接很好地解释了link1和link2。因此,在异步脚本中保持数据层是不可靠的,因为它不能保证您的脚本在gtag脚本之前执行。
https://stackoverflow.com/questions/50194222
复制相似问题