js中引入其他js的方法
最近在做一个需求,遇到了一个问题,html页面中引入一堆js,导致html页面代码看起来特别不美观,于是想着如何把所有的js引入到一个js内,然后只在html页面引入一个js,这样页面看起来就简洁多了,于是就做了如下的内容:
在shuilangyizu.js中引入多个其他js的代码:
var script1=document.createElement('script');//创建script标签节点 script1.setAttribute('type','text/javascript');//设置script类型 script1.setAttribute('src','http://pv.sohu.com/cityjson?ie=utf-8');//设置js地址 document.body.appendChild(script1);//将js追加为body的子标签 //判断script1是否加载成功 script1.onload=script1.onreadystatechange=function(){ //如果script1加载成功则创建script2引入,这样就不会由于后面的js依赖前面的js导致后面的js先加载而导致程序报错 if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){ var script2=document.createElement('script'); script2.setAttribute('type','text/javascript'); script2.setAttribute('src','http://www.shuilangyizu.top/js/jquery-2.1.4.js'); document.body.appendChild(script2); script2.onload=script2.onreadystatechange=function(){ if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){ var script3=document.createElement('script'); script3.setAttribute('type','text/javascript'); script3.setAttribute('src','http://www.shuilangyizu.top/js/clipboard.min.js'); document.body.appendChild(script3); script3.onload=script3.onreadystatechange=function(){ if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){ var script4=document.createElement('script'); script4.setAttribute('type','text/javascript'); script4.setAttribute('src','http://www.shuilangyizu.top/js/jquery-weui.js'); document.body.appendChild(script4); script4.onload=script4.onreadystatechange=function(){ if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){ var script5=document.createElement('script'); script5.setAttribute('type','text/javascript'); script5.setAttribute('src','http://www.shuilangyizu.top/js/wechat.js'); document.body.appendChild(script5); } } } } } } } }
然后将shuilangyizu.js引入html页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js中引入多个js测试</title> </head> <body ontouchstart> <div align="center" style="margin-top: 50px;"> <span class="ceshi">ceshi</span> </div> <script type="text/javascript" src="http://www.shuilangyizu.top/js/shuilangyizu.js"></script> </body> </html>
这样就成功了!!!