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>

這樣就成功了!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM