为什么Google Analytics会动态地将JavaScript注入页面 [英] Why does Google Analytics dynamically inject javascript into the page

查看:84
本文介绍了为什么Google Analytics会动态地将JavaScript注入页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 (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 async =truetype =text / javascriptsrc =http://www.google-analytics.com/ga.js>< / script> 

我能看到的唯一原因是他们有一个不同的SSL子域。如果不是,那么是否有任何理由使用这种脚本注入技术?
$ b

解决方案

能够根据父页面的协议提供 http https 是一个原因。 / p>

  • 由于脚本是通过运行JS代码插入的脚本标签注入的,因此它不会阻止页面加载。这是另一个原因。但是,通过新的HTML5 async 属性也可以很好地实现这一点(但这与旧版浏览器不兼容 - 而且GA绝对需要几乎所有的人都可以兼容)



  • Why do I need to use:

    (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);
    })();
    

    Instead of:

    <script async="true" type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>
    

    The only reason I can see is that they have a different subdomain for SSL. If it weren't for that is there any reason to use this script injection technique?

    解决方案

    1. Being able to serve out http or https depending on the protocol of the parent page is one reason.

    2. As the script is injected via a script tag inserted via running JS code, it does not block page loading. This is another reason. But this can very well be achieved via the new HTML5 async attribute too (but this is not compatible with older browsers - and GA absolutely needs to be compatible with pretty much all of them)

    这篇关于为什么Google Analytics会动态地将JavaScript注入页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆