
1、动态的插入script标签来加载脚本。
functionloadScript(url,callback){
constscript=document.createElement('script');
script.type='text/javascript';
//处理IE
if(script.readyState){
script.onreadystatechange=function(){
if(script.readyState==='loaded'||script.readyState==='complete'){
script.onreadystatechange=null;
callback();
}
}
}else{
//处理其他浏览器的情况
script.onload=function(){
callback();
}
}
script.src=url;
document.body.append(script);
}
//动态加载js
loadScript('file.js',function(){
console.log('加载完成');
})
2、通过xhr方式加载js文件,不过通过这种方式的话,就可能会面临着跨域的问题。
constxhr=newXMLHttpRequest();
xhr.open('get','file.js');
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status>=200&&xhr.status<300||xhr.status===304){
constscript=document.createElement('script');
script.type='text/javascript';
script.text=xhr.responseText;
document.body.append(script);
}
}
}
3、将多个js文件合并为同一个并压缩。
目前,大多数浏览器已经支持并行下载js文件,但并行下载仍有一定数量的限制(基于浏览器,一些浏览器只能下载4个)。此外,每个js文件都需要建立一个额外的http连接,并且4个25KB的文件比100KB的文件大。因此,最好将多个js文件合并为同一个并压缩代码。
以上就是javascript动态加载js文件的方法,希望对大家有所帮助。更多Javascript学习指路:Javascript
原文来自:https://www.py.cn© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容