您可以通过自己的服务器代理Google Analytics(分析)脚本,将其保存在本地,并每小时自动更新文件,以确保该文件始终是Google的最新版本。
我已经在几个站点上做到了,而且一切正常。
NodeJS / MEAN Stack中的Google Analytics(分析)代理路由
这就是我在使用MEAN堆栈构建的博客上实现它的方式。
router.get('/analytics.js', function (req, res, next) {
var fileUrl = 'http://www.google-analytics.com/analytics.js';
var filePath = path.resolve('/content/analytics.js');
// ensure file exists and is less than 1 hour old
fs.stat(filePath, function (err, stats) {
if (err) {
// file doesn't exist so download and create it
updateFileAndReturn();
} else {
// file exists so ensure it's not stale
if (moment().diff(stats.mtime, 'minutes') > 60) {
updateFileAndReturn();
} else {
returnFile();
}
}
});
// update file from remote url then send to client
function updateFileAndReturn() {
request(fileUrl, function (error, response, body) {
fs.writeFileSync(filePath, body);
returnFile();
});
}
// send file to client
function returnFile() {
res.set('Cache-Control', 'public, max-age=' + oneWeekSeconds);
res.sendFile(filePath);
}
});
ASP.NET MVC中的Google Analytics(分析)代理操作方法
这就是我在使用ASP.NET MVC构建的其他网站上实现它的方式。
public class ProxyController : BaseController
{
[Compress]
public ActionResult GoogleAnalytics()
{
var fileUrl = "https://ssl.google-analytics.com/ga.js";
var filePath = Server.MapPath("~/scripts/analytics.js");
// ensure file exists
if (!System.IO.File.Exists(filePath))
UpdateFile(fileUrl, filePath);
// ensure file is less than 1 hour old
var lastModified = System.IO.File.GetLastWriteTime(filePath);
if((DateTime.Now - lastModified).TotalMinutes > 60)
UpdateFile(fileUrl, filePath);
// enable caching for 1 week for page speed score
Response.AddHeader("Cache-Control", "max-age=604800");
return JavaScript(System.IO.File.ReadAllText(filePath));
}
private void UpdateFile(string fileUrl, string filePath)
{
using (var response = WebRequest.Create(fileUrl).GetResponse())
using (var dataStream = response.GetResponseStream())
using (var reader = new StreamReader(dataStream))
{
var body = reader.ReadToEnd();
System.IO.File.WriteAllText(filePath, body);
}
}
}
这是MVC ProxyController用于Gzip压缩的CompressAttribute
public class CompressAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(encodingsAccepted)) return;
encodingsAccepted = encodingsAccepted.ToLowerInvariant();
var response = filterContext.HttpContext.Response;
if (encodingsAccepted.Contains("gzip"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (encodingsAccepted.Contains("deflate"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
更新了Google Analytics(分析)脚本
在客户端,我会在分析路径上附加当前日期(直到一小时),以使浏览器使用的缓存版本不会超过一个小时。
<!-- analytics -->
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '/analytics.js?d=' + new Date().toISOString().slice(0, 13), 'ga');
</script>