html中动态加载
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.onreadystatechange= function () {
if (this.readyState == 'complete')
callback();
}
script.onload= function(){
callback();
}
script.src= 'helper.js';
head.appendChild(script);
我设了2个事件监听函数, 因为在ie中使用onreadystatechange, 而gecko,webkit 浏览器和opera都支持onload。事实上this.readyState == 'complete'并不能工作的很好,理论上状态的变化是如下步骤:
0 uninitialized
1 loading
2 loaded
3 interactive
4 complete
但是有些状态会被跳过。根据经验在ie7中,只能获得loaded和completed中的一个,不能都出现,原因也许是对判断是不是从cache中读取影响了状态的变化,也可能是其他原因。最好把判断条件改成this.readyState == 'loaded' || this.readyState == 'complete'
参考jQuery的实现我们最后实现为:
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.onload = script.onreadystatechange = function() {
if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete" ) {
help();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
} };
script.src= 'helper.js';
head.appendChild(script);
还有一种简单的情况就是可以把help()的调用写在helper.js的最后,那么可以保证在helper.js在加载完后能自动调用help(),当然最后还要能这样是不是适合你的应用。
另外需要注意:
1.因为script标签的src可以跨域访问资源,所以这种方法可以模拟ajax,解决ajax跨域访问的问题。
2.如果用ajax返回的html代码中包含script,则直接用innerHTML插入到dom中是不能使html中的script起作用的。粗略的看了下jQuery().html(html)的原代码,jQuery也是先解析传入的参数,剥离其中的script代码,动态创建script标签,所用jQuery的html方法添加进dom的html如果包含script是可以执行的。如:
jQuery("#content").html("<script>alert('aa');<\/script>");