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

查看:21
本文介绍了为什么 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="true" type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>

我能看到的唯一原因是他们有不同的 SSL 子域.如果不是这样,有什么理由使用这种脚本注入技术吗?

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. 能够根据父页面的协议提供 httphttps 是一个原因.

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

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天全站免登陆