使用Javascript检查是否已加载jquery

246

我正在尝试检查我的Jquery Library是否加载到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>

3
请勿在“$(document).Ready”中使用大写字母R。 - Serigan
12
警告(如果window.$存在,则为1;否则为0)。 - Thielicious
1
你为什么还在使用旧的xhtml标准?直接使用<!doctype html>就好了。 - Luke
如果$(document)准备函数运行,则jquery已加载。因此,您可以简单地执行$(document).ready(function(){ alert("Ready!"); });。当然,如果jquery无法运行,这不会显示警报。但是,如果您只需要验证是否正确引用了jquery库,则足够了。 - ToolmakerSteve
尝试 { $.fn.jquery; alert(1); } catch(err) { alert(0); } - user815693
人们还在使用Jquery吗? - SoftwareSavant
12个回答

462

有些不对劲

你正在使用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");
    }
}

2
jQuery未定义时,这仍会抛出错误。您需要检查window.jQuery - gilly3
1
@gilly3:是啊,可恶的作用域问题。已经解决了。 - BoltClock
3
他们两个都在根目录吗?你的“src”前面有一个斜杠,这意味着它正在根目录中寻找。 - BoltClock
好的解决方案,但如果文档准备就绪时还有其他代码运行怎么办?我的代码就有这种情况,而且似乎文档准备就绪在窗口加载之前运行。 - learnerplates
这个方法对我也起作用了。只是一种减少代码行数的变体,将if/else结构放在三元操作中,并且可以将其保持在一行中:alert( window.jQuery ? "success" : "failure" ); - jerik
显示剩余6条评论

52
根据这个链接:
if (typeof jQuery == 'undefined') {
    // jQuery IS NOT loaded, do stuff here.
}
还有一些在链接的评论中,比如:
if (typeof jQuery == 'function') {...}

//or

if (typeof $ == 'function') {...}

// or

if (jQuery) {
    console.log("jquery is loaded");
} else {
    console.log("Not loaded");
}
希望这涵盖了完成这件事情的大部分好方法!!

2
@JakeN 在一段时间之后,除非编辑帖子,否则无法撤消反对票。但是,这个帖子有一个问题:如果 jQuery 没有被加载,if (jQuery) { 将在严格模式下抛出错误,因此最后的代码片段是一个糟糕的建议。 - JLRishe
@TusharShukla 对于 if (typeof $== 'function') {...},为什么美元符号和两个等号之间没有空格? - Grace
@Grace 这是一个缩进问题,已经修复了。 - Tushar Shukla

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

26
你可以在检查网页时的控制台选项卡上快速执行此操作。
例如:
$ === jQuery
如果返回true,意味着它已经加载。

如果jQuery未加载,这将引发异常:Uncaught ReferenceError: jQuery is not defined - Batkins
1
jQuery可能不会作为“jQuery”加载,而只能作为$。 - Tom Anderson
@TomAnderson,这样做可能有些不必要,因为jQuery非常流行和特定,很难有人会意外地创建一个具有该名称的变量。但是,人们确实会将jQuery作为$导入吗? - Vitaliy Terziev

11

只需进行一些小的修改,就有可能解决这个问题:

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

使用 window.onload = function() 替代 $(document).Ready(function()


8

注意:不要使用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";
}

4

更新:

现在我已经在生产环境中使用了这个代码,它的运行效果非常好。

请确保您确实正在加载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();


3
如果 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 );
})();

这种方法可以用于任何变量,您正在等待它出现。


1
下面是一个通用的跨浏览器JQuery加载器。它检查文档的DOM、HTML、CSS、文件和资源是否完全加载,以及JQuery文件本身是否被解析和运行。这个检查器适用于旧版浏览器,并支持旧版Internet Explorer(v.4-11),以及各种追溯到2001年的用户代理。它仅受到在这些浏览器中恰好没有错误的各种版本JQuery的限制。不幸的是,很多版本都存在问题。
请记住,在JQuery文件及其使用的任何资源下载、解析和JIT编译之前,您无法运行依赖于JQuery的脚本。您也可以使用下面的代码测试浏览器是否在其他资源下载之前尽早处理DOM,并运行非JQuery早期脚本来处理DOM。下面的第一个函数演示了这个特性。这假设只有DOM被构建,而许多CSS、图像和JavaScript文件仍未被下载。如果您需要延迟脚本在JQuery和其他库之前尽早下载,并出于某种原因操作DOM,则此功能非常有用。
    // 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)");
        };
    };

0
这对我来说很有效,当脚本有时会在页面中间运行(.net部分)或在页面完全加载后运行(jquery.load()调用)。
window.onload = function(){
   ... jQuery Statements ...
}
if (window.jQuery!==undefined)
    window.onload();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接