动态载入js并执行(未成功)
授权方式:署名,非商业用途,保持一致,转载时请务必以超链接(http://www.fwolf.com/blog/post/223)的形式标明文章原始出处和作者信息及本声明。说是未成功,也包含了并未失败的含义,只是没有完全达到预期的目的罢了。
最初的想法是这样的,我零星的写过一些小文章或者小工具,都是使用html语言写的,但处于方便保存/转移/备份/浏览的目的,html中所有的内容全部都包含在一个文件当中,不使用图片,css和javascript也都直接包含在文件中。现在我想在这些文章和工具中添加一些统计代码和adsense代码,就想到了如果能有一个js文件,把统计代码和adsense代码都写在里面,然后在那些单独的html文件当中包含一下这个js文件就可以了,这样可维护性就大大的增强了。
首先要排除的是innerHTML方式,因为这种方式只能写入静态内容,写入js代码虽然能够成功,但被写入的代码却不会被执行。所以,最后采用了appendChild的方式,结果如下:
首先在html也中引用js文件:
<script src=”stat_51_la.js” type=”text/javascript”></script>
然后,具体被引用的js文件内容是这样的:
{
//重定向document.write的输出方向
document.write = function(s)
{
document.getElementById(’stat_51_la’).innerHTML += s;
return false;
}
var s = document.createElement(”script”);
s.type=”text/javascript”; s.src=”http://js.users.51.la/272422.js”;
//document.getElementsByTagName(”body”)[0].appendChild(s);
document.body.appendChild(s);
}
stat_51_la();
思路介绍:先看下面那段代码,就是document.createElement往后的部分,主要思路是通过document.createElement创建一个script对象,然后对他的属性进行赋值,尤其是src属性,代表这要引用的js script文件的uri,最后通过document.body.appendChild(s);把这个script对象添加为body的最后一个对象,实现js文件的动态载入,并且可以正确的执行所载入的js代码。但如果只作这么多工作的话,当动态载入的js文件中有document.write方法时,在IE下没有反应,但在Mozilla Firefox 下就会让你原来的网页消失,只显示document.write出来的内容,所要就要用到document.write = function(s)部分,重新定义document.write函数,把输出重定向到div id=”stat_51_la”当中,就能够比较好的解决这个问题了。
看起来已经解决了问题,并且用在51.la统计代码上效果很好,但在嵌入adsense代码的时候遇到了问题,大概检查了一下,好像是adsense也用到了类似的方法,两种相同的方法一嵌套,就变样了,实在是头大,没有精力再深入的查找原因了,就此打住,像adsense这样复杂一些的应用还是用后台脚本实现更方便。
![[Bloglines]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/bloglines.png)
![[co.mments]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/comments.png)
![[del.icio.us]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/digg.png)
![[diigo]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/diigo.png)
![[Facebook]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/facebook.png)
![[Furl]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/furl.png)
![[Google]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/google.png)
![[MySpace]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/myspace.png)
![[Reddit]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/reddit.png)
![[Rojo]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/rojo.png)
![[Slashdot]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/slashdot.png)
![[StumbleUpon]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Technorati]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/technorati.png)
![[Windows Live]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/windowslive.png)
![[Yahoo!]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/yahoo.png)
![[Email]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/email.png)