我试图检查我的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>

当前回答

有些事情不对劲

好吧,您正在使用jQuery来检查jQuery的存在。如果jQuery没有加载,那么$()甚至不会运行,你的回调也不会执行,除非你正在使用另一个库,而这个库恰好共享相同的$()语法。

删除$(document).ready()(使用类似window的东西)。onload相反):

window.onload = function() {
    if (window.jQuery) {  
        // jQuery is loaded  
        alert("Yeah!");
    } else {
        // jQuery is not loaded
        alert("Doesn't Work");
    }
}

其他回答

如果jQuery是异步加载的,你可以等待它被定义,每一段时间检查它:

(function() {
    var a = setInterval( function() {
        if ( typeof window.jQuery === 'undefined' ) {
            return;
        }
        clearInterval( a );

        console.log( 'jQuery is loaded' ); // call your function with jQuery instead of this
    }, 500 );
})();

这个方法可以用于任何变量,你等待出现。

一个快速的方法是在开发人员控制台中运行jQuery命令。在任何浏览器上按F12并尝试访问任何元素。

 $("#sideTab2").css("background-color", "yellow");

注意:不要用jQuery来测试你的jQuery(不是很明显)

使用jQuery

if ('undefined' == typeof window.jQuery) {
    $('#selector').appendTo('jQuery is NOT working');
} else {
    $('#selector').appendTo('jQuery is working');
}

使用javaScript

if ('undefined' == typeof window.jQuery) {
    document.getElementById('selector').innerHTML = "jQuery is NOT working";
} else {
    document.getElementById('selector').innerHTML = "jQuery is working";
}

你只需要输入 窗口。jQuery控制台。如果它返回一个函数(e,n)…确认jquery加载成功,运行正常。

按照这个链接:

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!!