我试图检查我的Jquery库是否加载到我的HTML页面。我正在检查它是否工作,但有些地方不太对劲。以下是我所拥有的:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="/query-1.6.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if (jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
});
</script>
按照这个链接:
if (typeof jQuery == 'undefined') {
// jQuery IS NOT loaded, do stuff here.
}
there are a few more in comments of the link as well like,
if (typeof jQuery == 'function') {...}
//or
if (typeof $ == 'function') {...}
// or
if (jQuery) {
console.log("jquery is loaded");
} else {
console.log("Not loaded");
}
Hope this covers most of the good ways to get this thing done!!
更新:
现在我在生产中使用它,它就像一个魅力。
请确保您确实在加载jQuery,否则会导致无限循环。我建议你添加一个计数器,如果你需要的话可以打破它:
(async() => {
console.log("waiting for jQuery");
while(!window.hasOwnProperty("jQuery")) {
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log("jQuery is loaded.");
})();
旧的回答:
您可以检查它是否存在,如果不存在,则动态加载它。
function loadScript(src) {
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = src;
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}
async function load(){
if (!window.jQuery){
await loadScript(`https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js`);
}
console.log(jQuery);
}
load();