javascript代码加载优化方法

  下面我们通过这个例子介绍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);

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