2016-09-30 2 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を使用してjqueryファイルを追加すると利用できなくなるため、利用可能なときにonload listenerを追加する必要がありません。ここで

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

clickイベントを$(document).readyに入れて、DOMが準備完了のときにイベントが発生するようにします。

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>

です
関連する問題