2016-09-30 88 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>