我有一个外部JS文件来管理页面中的所有脚本。我想在此文件中编写一些代码来检查是否已加载jquery插件和(如果没有)加载它!
我尝试使用以下代码开始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>
但是它没有执行警报对话框。
当您使用脚本添加jquery文件时,该文件将不可用,因此您必须添加onload侦听器以检测何时可用。
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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句