您可以通过自己的服务器代理谷歌分析脚本,将其保存在本地,并每小时自动更新文件,以确保它始终是谷歌的最新版本。
我已经在几个网站上做了这个,现在一切都很好。
谷歌NodeJS / MEAN Stack中的分析代理路由
这就是我如何在我的博客上实现它,它是用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
这就是我如何在其他用ASP构建的网站上实现它的。净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);
}
}
}
更新谷歌分析脚本
在客户端,我将分析路径与当前日期附加到小时,这样浏览器就不会使用超过一小时前的缓存版本。
<!-- 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>