该如何加载google-analytics(或其他第三方)的JS
很多网站为了获取用户访问网站的统计信息,使用了google-analytics或其他分析网站(下面的讨论中只提google-analytics, 简称ga)。注册ga后,ga就会生成一段js脚本,很多人直接把这段js复制到<body>的最后面就完事(包括 博客园、CSDN、BlogJava)。可是ga自动生成的这段JS真的就是最合理的吗?
<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-123456-1"); pageTracker._trackPageview(); } catch(err) {}</script>
看这段代码,使用document.write来加载JS,注意了,这样加载js是阻塞加载的,就是这个js没加载完,后面的所有资源和JS都不能下载和执行。可能你会觉的这段代码在body的最后面,后没已经没内容,没什么会阻塞的了。
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function(){
$.get(“http://www.126.com/”);
});
</script>
</head>
<body>
<script type=”text/javascript”>
var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
document.write(unescape(“%3Cscript src='” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));
</script>
<script type=”text/javascript”>
try {
var pageTracker = _gat._getTracker(“UA-123456-1”);
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
<script type=”text/javascript”>
var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
var head = document.getElementsByTagName(“head”)[0] || document.documentElement;
var script = document.createElement(“script”);
script.src = gaJsHost + “google-analytics.com/ga.js”;var done = false; // 防止onload,onreadystatechange同时执行
// 加载完毕后执行,适应所有浏览器
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState === “loaded” || this.readyState === “complete”)){
done = true;
try {
var pageTracker = _gat._getTracker(“UA-123456-16”);
pageTracker._trackPageview();
} catch(err) {}
script.onload = script.onreadystatechange = null;
}
};
head.insertBefore(script,head.firstChild);
</script>
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); $.getScript(gaJsHost + "google-analytics.com/ga.js",function(){ try { var pageTracker = _gat._getTracker("UA-123456-16"); pageTracker._trackPageview(); } catch(err) {} });
有需要请查看:高性能WEB开发系列
本文出自 传播、沟通、分享,转载时请注明出处及相应链接。
本文永久链接: https://www.nickdd.cn/?p=504
一条评论
I hope, it’s OK