use*_*666 14 html javascript jquery google-analytics
新的Google Analytics代码如下所示:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-0000000-00']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
Run Code Online (Sandbox Code Playgroud)
如何将全新的Google Analytics异步跟踪代码移动到外部JavaScript文件中?
我特别要问"var _gaq = _gaq || []; [...]"因为我知道可以移动其余部分,例如
的index.html
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-0000000-00']);
_gaq.push(['_trackPageview']);
</script>
<script src="include.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)
include.js
function includeGA()
{
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
}
$(document).ready(function()
{
includeGA();
});
Run Code Online (Sandbox Code Playgroud)
我已经尝试将"var _gaq = _gaq || []; [...]"代码放到不同的位置,但没有任何效果.
Vis*_*rma 17
您不应将GA代码置于函数中,原因有两个:
批评使用外部JS进行GA代码的人在这里有点不对.通过在js embed中引入async属性,它是有道理的.我将这个GA代码保存在外部js中,并将其异步嵌入到文档的头部.两个好处:
所以HTML将成为:
<head>
<script type="text/javascript" src="static/scripts.js" async></script>
</head>
Run Code Online (Sandbox Code Playgroud)
并将scripts.js:
var _gaq=_gaq||[];
_gaq.push(['_setAccount','UA-XXXXXXXX-1']);
_gaq.push(['_setDomainName','.domain.net']);
_gaq.push(['_trackPageview']);
(function(){
var ga=document.createElement('script');
ga.type='text/javascript';
ga.async=true;
ga.src=('https:'==document.location.protocol?'https://ssl':'http://www')+'.google-analytics.com/ga.js';
var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(ga,s)
})();
Run Code Online (Sandbox Code Playgroud)
然后再说一遍:不要将您的Google Async代码段放在外部文件中,因为它会阻止其他内容下载.拥有异步跟踪代码的要点是使其并行.
如果您使用异步GA,只需将其放在内联脚本标记中的文档顶部.这也是Google Analytics网站上的推荐:
在您的页面或模板可能使用的任何其他脚本之后,将异步代码段插入页面部分的 底部
<head>.
| 归档时间: |
|
| 查看次数: |
23006 次 |
| 最近记录: |