ajax方式加载script文件用法实例详解

ajax方式加载script文件用法实例详解,第1张

利用ajax方式,把script文件代码从后台加载到前台,然后对加载到的内容通过eval()执行代码。


第二种是,动态创建一个script标签,设置其src属性,通过把script标签插入到页面head来加载js,相当于在head中写了一个,只不过这个script标签是用js动态创建的

比如说是我们要动态地加载一个callbakc.js,我们就需要这样一个script标签:

如下代码就是如何通过js来创建这个标签(并且加到head中):

var head= document.getElementsByTagName('head')[0]; 
var script= document.createElement('script'); 
script.type= 'text/javascript'; 
script.src= 'call.js'; 
head.appendChild(script);

当加载完call.js, 我们就要调用其中的方法。


不过在header.appendChild(script)之后我们不能马上调用其中的js。


因为浏览器是异步加载这个js的,我们不知道他什么时候加载完。


然而我们可以通过监听事件的办法来判断helper.js是否加载完成。


(假设call.js中有一个callback方法)

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("alert('aa');");

以上就是ajax方式加载script文件用法实例详解的详细内容,更多请关注php中文网其它相关文章!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/239825.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2018-05-30
下一篇 2018-05-30

发表评论

登录后才能评论

评论列表(0条)

保存