我试图检查我的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");
    }
}

if ('undefined' == typeof window.jQuery) {
    // jQuery not present
} else {
    // jQuery present
}

只是一个可能真正解决问题的小修改:

window.onload = function() {
   if (window.jQuery) {  
       // jQuery is loaded  
       alert("Yeah!");
   } else {
    location.reload();
   }
}

而不是$(document). ready (function()使用窗口。Onload = function()。


按照这个链接:

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命令。在任何浏览器上按F12并尝试访问任何元素。

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


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


在检查网页时,您可以在控制台选项卡上快速完成此操作。

E.g:

$ === jQuery

如果它返回真,就意味着它已加载。


如果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来测试你的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,否则会导致无限循环。我建议你添加一个计数器,如果你需要的话可以打破它:

(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();


下面是一个通用的跨浏览器JQuery加载器。它检查文档的DOM、HTML、CSS、文件和资源是否完全加载,以及JQuery文件本身是否已解析并正在运行。这个检查器可以在旧的浏览器中工作,并支持旧的Internet Explorer (v. 4-11)以及2001年以来的各种用户代理。它只受到JQuery本身的各种版本的限制,这些版本恰好在这些浏览器中没有bug。可悲的是,很多人都不是。

Keep in mind, you cannot run scripts that rely on JQuery till the JQuery files and any resources used are downloaded, parsed, and JIT compiled. You can also use the code below to test if DOM is processed early in the browser before other resources are downloaded, and run non-JQuery early scripts to work with the DOM. The first function below demonstrates that feature. This assumes only the DOM is built and many CSS, images, and JavaScript files are still not downloaded. This is useful if you need deferred scripts to download early before JQuery and other libraries and manipulate the DOM for some reason.

    // EARLY JAVASCRIPT DOM PROCESSING (non-JQuery)
    // Function to run as soon as the HTML is parsed and DOM rendered.
    function DOMStart(state) {
        if (state == null) {
            state = "Unknown";
        }
        alert('DOM State: ' + state);
    };

    // FULLY LOADED WINDOW/DOCUMENT JAVASCRIPT PROCESSING, plus JQUERY CHECK
    // TEST IF JQUERY IS LOADED (without using JQuery)
    // Function to run as soon as all resources associated with the document are ready and JQuery script files are loaded.

    function JQueryStart(state) {
        if (state == null) {
            state = "Unknown";
        }
        alert('JQuery State: ' + state);

        //if (typeof window.jQuery !== 'undefined') { // Alt. Version #2 check
        if (window.jQuery) {
            // jquery is loaded...
            alert("JQuery is loaded.");

            // JQuery is downloaded. Now use JQuery to test if
            // the document object model is fully
            // loaded again from the point of view of JQuery.
            // In most cases it is based on logic below.
            // It is possible to load this function only when the
            // DOM is ready instead of the whole document and all
            // its files are ready and run a timer to detect when 
            // "window.jQuery" above is true. That would allow you
            // to know JQuery is downloaded prior to the DOM and 
            // utilize it earlier.

            $(document).ready(function () {

                // ======== Begin JQuery Scripts ======== 


            });
        } else {
            // JQuery did not load...
            console.log("JQuery failed to load!");
            alert("JQuery failed to load!");
        }
    };


    // OLD BROWSER PAGE LOADER: This document loading check 
    // supports older browsers, including IE4+ and many older 
    // browsers like Firefox (2006), early Chrome (2010), etc.
    // Note: "interactive" is when the document has finished
    // loading and the document has been parsed and DOM is complete,
    // but sub-resources such as scripts, images, style sheets and
    // frames are still loading. "complete" is when all resources
    // are loaded and right before the "Window.load event fires.
    // Note: "document.onreadystatechange" has support in very old
    // browsers amd may have support from IE4+, It fires as each
    // state of the docuent load process changes below. IE 4-9 only
    // supported "readyState" of "complete".

    // If the document is already loaded and those events fired, run the JQuery function above.

    if (document.readyState) {
        if (document.readyState === "complete" // IE 4-9 only knows "complete"
            || document.readyState === "loaded") {
            JQueryStart("Document fully loaded (early)");
        } else {
            // New browsers should run scripts when the HTML is
            // parsed and the DOM built. Older IE browsers will
            // not support the "DOMContentLoaded" event and instead
            // fire when complete below. This allows newer browsers
            // to fire only when the HTML DOM is ready, which happens
            // right after the readyState=interactive fires.

            if (window.addEventListener) {
                // Listen for the "DOMContentLoaded" event, which occurs
                // after "interactive" but when the HTML DOM is complete.
                // This means the DOM is ready but other resources style 
                // sheets, other scripts, images, etc. may not be.

                window.addEventListener('load', function () {
                    JQueryStart("Window fully loaded (2)");
                }, false);
                window.addEventListener('DOMContentLoaded', function () {
                    DOMStart("DOM complete (early)");
                }, false);
            } else {

                // Run the older page "onreadystatechange" for older
                // browsers. Below, runs when page resources are not
                // yet fully loaded, so set up event listeners based
                // on needs of old/new web browsers script support.
                // This fires each time the document readyState changes,
                // except in IE 4-9 that only supports "complete". Below,
                // the DOM is loaded and parsed, but adding "interactive"
                // to the condition below means other resources like CSS, 
                // images, etc may not have completed yet.
                // Note: Add "interactive" below if needing to run early 
                // scripts as soon as the DOM is complete, and do not require 
                // styles sheets, script files, images, other resources, etc.
                // Note: "interactive" fires before "DOMContentLoaded", but in 
                // IE 9 - 11 fires too early before parsing.

                var isDone = false;
                document.onreadystatechange = function () {
                    if (document.readyState === "complete" // IE 4-9 only knows "complete"
                        || document.readyState === "loaded") {
                        if (!isDone) {
                            isDone = true;
                            JQueryStart("Document fully loaded");
                        }
                    }
                    else if (document.readyState === "interactive") {
                        DOMStart("Document interactive (early)");
                    }
                };
            }
        }
    } else {
        // This is a fallback event format that works well in many older browsers.
        window.onload = function () {
            JQueryStart("Window fully loaded (1)");
        };
    };