Skip to content

Instantly share code, notes, and snippets.

@ambar
Created December 21, 2011 12:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ambar/1505881 to your computer and use it in GitHub Desktop.
Save ambar/1505881 to your computer and use it in GitHub Desktop.
如何改善百度统计引入代码
<html>
<head>
<title></title>
</head>
<body>
<div>
<script>
document.body.appendChild( document.createElement('script') )
</script>
</div>
</body>
</html>
(function(doc,id) {
var t = doc.createElement('script');
t.async = true;
t.src = '//hm.baidu.com/h.js?'+id;
(doc.head || doc.body).appendChild(t);
})(document,'baidu_hash_id')
(function(doc,tag,src) {
var e = doc.createElement(tag), s = doc.getElementsByTagName(tag)[0]; e.async = e.src = src; s.parentNode.insertBefore(e, s);
})(document,'script','//domain/analytics.js')
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fhash_id' type='text/javascript'%3E%3C/script%3E"));
require 'sinatra'
get '/h.js' do
sleep(2)
content_type 'application/javascript'
<<-js
(function (msg) {
var now = function () { return +new Date() }
var begin = now();
while (now() - begin < 2000) {}
console.log(msg, now());
})('h.js loaded. ');
js
end
@ambar
Copy link
Author

ambar commented Dec 26, 2011

据反应,部分宽带连 hm.baidu.com 都访问不了

@ambar
Copy link
Author

ambar commented Dec 31, 2011

ie6_crash.html

总会发现有人没把引入脚本放在 body 之前。
此时,如果 script 标签在 body 的其他标签里面,再操作文档的话,ie6 将崩溃,提示“已中止操作”。修复见:improved_v2.js ,ie6 甚至可能 document.body 引用是 null。
据称,页面上有未结束的 base 标签也会有影响。

http://mathiasbynens.be/notes/async-analytics-snippet

@ThomasLau
Copy link

cool,不过见过一个更好的解决方法,是:

<div id="google-analytics">
        <script>
        setTimeout(function(){
          (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','https://www.google-analytics.com/analytics.js','ga');

          ga('create', 'UA-22801497-2', 'zjmainstay.cn');
          ga('send', 'pageview');
        }, 1000);
        </script>
    </div>

@guorenxi
Copy link

guorenxi commented Feb 6, 2022

Great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment