2016-09-30 136 views
0

我有一個外部JS文件來管理我的頁面中的所有腳本。 我想在這個文件中寫一些代碼來檢查jquery插件是否被加載,並且(如果沒有)加載它!如何檢查jquery是否從外部JS文件加載?

我想開始我的myScripts.js這個代碼文件:

if (typeof jQuery == 'undefined') { 
    var script = document.createElement('script'); 
    script.type = "text/javascript"; 
    script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"; 
    document.getElementsByTagName('head')[0].appendChild(script); 
} 

而且在我的index.html

我這樣做:

<!DOCTYPE html> 
<html lang="pt-br"> 

    <head> 
     <script src="myScripts.js"></script> 

    </head> 

    <body> 

     <button id="test">test</button> 

     <script> 

     $('#test').click(function() { 

      alert('clicked'); 

     }); 

     </script> 
    </body> 

</html> 

但它不執行警報對話框。有什麼問題?

回答

0

當您添加使用script.it將不可用,所以你需要添加的onload監聽器檢測到時,它可用jQuery的文件。

function fnjquery() { 
    $('#test').click(function() { 

     alert('clicked'); 

    }); 
} 

if(typeof jQuery=='undefined') { 
    var headTag = document.getElementsByTagName("head")[0]; 
    var jqTag = document.createElement('script'); 
    jqTag.type = 'text/javascript'; 
    jqTag.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'; 
    jqTag.onload = fnjquery; 
    headTag.appendChild(jqTag); 
} else { 
    fnjquery(); 
} 
1

$(document).ready附上click事件以確保當DOM準備好時事件被觸發。

$(document).ready(function(){ 
$('#test').click(function() { 

      alert('clicked'); 

     }); 
}); 
0

這裏是一個工作Fiddle

function myJQueryCode() { 
 
    //Do stuff with jQuery 
 
    $('#test').click(function() { 
 
      alert('clicked'); 
 
     }); 
 
} 
 

 
if(typeof jQuery=='undefined') { 
 
    var headTag = document.getElementsByTagName("head")[0]; 
 
    var jqTag = document.createElement('script'); 
 
    jqTag.type = 'text/javascript'; 
 
    jqTag.src = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'; 
 
    jqTag.onload = myJQueryCode; 
 
    headTag.appendChild(jqTag); 
 
} else { 
 
    myJQueryCode(); 
 
}
<button id="test"> 
 
click 
 
</button>