【问题标题】:Checking if jquery is loaded using Javascript检查是否使用 Javascript 加载了 jquery
【发布时间】:2011-11-12 14:25:19
【问题描述】:

我正在尝试检查我的 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>

【问题讨论】:

  • 不要在 "$(document).Ready" 中使用大写字母 R
  • alert(window.$?1:0)
  • 为什么还在使用旧的 xhtml 标准?只需改用&lt;!doctype html&gt;
  • 如果$(document) ready 函数完全运行,则加载 jquery。所以你可以简单地做$(document).ready(function(){ alert("Ready!"); }); 当然,如果 jquery 无法运行,这不会显示警报。但是,如果您只需要验证您是否正确引用了 jquery 库,这就足够了。

标签: javascript jquery


【解决方案1】:

有点不对劲

嗯,您正在使用 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 未定义时,这仍然会引发错误。你需要检查window.jQuery
  • @gilly3:是的,讨厌的范围界定问题。固定。
  • 我的 jquery-1.6.3.min.js 文件与 html 文件位于同一目录中。不知道为什么它不加载。
  • @DmainEvent:它们都在根目录下吗?您的src 有一个前导/,这意味着它正在查找根目录。
  • 其实没有。让我改变一下,试一试。
【解决方案2】:

根据this链接:

if (typeof jQuery == 'undefined') {
    // jQuery IS NOT loaded, do stuff here.
}


链接的 cmets 中还有一些,例如,

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

//or

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

// or

if (jQuery) {
    alert("jquery is loaded");
} else {
    alert("Not loaded");
}


希望这涵盖了完成这件事的大部分好方法!

【讨论】:

  • @JakeN 一定时间后,除非编辑帖子,否则无法撤消反对票。不过,这篇文章有一个问题:如果未加载 jQuery,if (jQuery) { 将在严格模式下抛出错误,因此最后一个代码 sn-p 是一个不好的建议。
【解决方案3】:
if ('undefined' == typeof window.jQuery) {
    // jQuery not present
} else {
    // jQuery present
}

【讨论】:

    【解决方案4】:

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

    例如:

    $ === jQuery
    

    如果返回true,则表示已加载。

    【讨论】:

    • 如果没有加载 jQuery,这将引发异常,但是:Uncaught ReferenceError: jQuery is not defined
    【解决方案5】:

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

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

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

    【讨论】:

      【解决方案6】:

      注意:不要使用 jQuery 来测试你的 jQuery

      ​​>

      当您使用其他用户提供的任何代码时,如果您想在您的窗口而不是alertconsole.log 上显示消息,那么请确保您使用的是javascript 而不是jquery。

      不是每个人都想使用alertconsole.log

      alert('jquery is working');
      console.log('jquery is working');
      

      下面的代码将无法显示消息
      因为我们在else 中使用了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";
      }
      

      【讨论】:

        【解决方案7】:

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

        此方法可用于任何变量,您正在等待出现。

        【讨论】:

          【解决方案8】:

          更新:

          现在我在生产中使用它,它就像一个魅力。

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

          【讨论】:

            【解决方案9】:

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

            请记住,在下载、解析和 JIT 编译 JQuery 文件和使用的任何资源之前,您无法运行依赖 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)");
                    };
                };
            

            【讨论】:

              【解决方案10】:

              你可以输入 window.jQuery 在控制台中。如果它返回一个函数(e,n)......然后确认jquery已加载并成功运行。

              【讨论】:

              • 虽然它可以工作并且有一些实用程序(例如,如果您只是想在第一次包含 jQuery 时检查您的 CDN 是否正常工作),但它对于以编程方式进行测试没有用处。例如,我的代码检查 jQuery 的存在以防 CDN 关闭(以回退到 jQuery 的本地副本),并区分通过 AJAX 等加载 HTML 时如何/是否分配事件(例如点击)
              【解决方案11】:

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

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

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2011-05-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-01-04
                • 1970-01-01
                相关资源
                最近更新 更多