佛山软件定制

[转]网站统计之javascript代码加载优化

原文地址:http://blog.atnet.cc/javascript/dynamic_append_script_tag/

 

我们通过一个例子来说明:

给你的网站加上代码统计!常用的方法是直接加统计代码到网页,但你的网页数量很多呢?

下面我们通过这个例子介绍1个更简单的方法:

我们用将统计代码保存到1个文件:文件路径:/config/counter.conf

统计代码如下:

<script type=”text/javascript”>
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-18744406-1']);
  _gaq.push(['_trackPageview']);

  (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>

 

我们用StreamReader将文件内容读出来,代码将不详细列出

我们需要一个页面来输出这段javascript代码:

页面:/do.ashx?args=GetCounter

 

string code = “读取到的统计代码”;
code = Regex.Replace(code, “[\']“,”\”");
code = Regex.Replace(code, “[\n\r]“, “”);
context.Response.Write(“document.write(‘”+code+”‘);”);

这样就能将输出的javascript添加到页面实现统计功能了!

我们只需在网页都引用的javascript文件中添加如下代码:

var _s=document.createElement(‘script’);
_s.type=’text/javascript’;
_s.src=’/do.ashx?args=GetCounter’;
var _fs=document.getElementsByTagName(“script”)[0];
_fs.parentNode.insertBefore(_s,_fs);

大功告成,统计代码不会显示在你的网页中,但事实上却已经加载到了你的网页!

 

原创文章转载请注明出处:http://blog.atnet.cc/javascript/dynamic_append_script_tag/

 

 

 

posted on 2010-09-30 16:25  New.min  阅读(380)  评论(0编辑  收藏  举报

导航