【问题标题】:check if jquery has been loaded, then load it if false检查是否已加载 jquery,如果为 false 则加载它
【发布时间】:2010-12-22 03:26:57
【问题描述】:

有谁知道如何检查 jquery 是否已加载(使用 javascript),如果尚未加载则加载它。

类似

if(!jQuery) {
    //load jquery file
}

【问题讨论】:

  • 感谢您的提醒!希望它实际上不必被调用。只是想增加一点冗余

标签: javascript jquery


【解决方案1】:

可能是这样的:

<script>
if(!window.jQuery)
{
   var script = document.createElement('script');
   script.type = "text/javascript";
   script.src = "path/to/jQuery";
   document.getElementsByTagName('head')[0].appendChild(script);
}
</script>

【讨论】:

  • 请注意,这假定文档有一个head,它可以将脚本元素附加到
  • @DanielLeCheminant 很好。如果是( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( script );
  • @Pawel 我已经看到一些实现在第一个脚本标记之前/之后插入元素,因为你知道必须有一个。
  • 我相信将脚本标签附加到正文中适用于所有浏览器。
  • 所以,总而言之;最安全的方法是: ( document.getElementsByTagName('head')[0] || document.getElementsByTagName('script')[0] ).appendChild( script );因为至少会有一个 script 标签的实例。
【解决方案2】:

避免使用“if (!jQuery)”,因为 IE 会返回错误:jQuery is 'undefined'

改为使用:if (typeof jQuery == 'undefined')

<script type="text/javascript">
if (typeof jQuery == 'undefined') {
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(script);
}
</script>

您还需要在将 JQuery 附加到标头后检查它是否已加载。否则,您将不得不等待 window.onload 事件,如果页面有图像,该事件会更慢。这是一个检查 JQuery 文件是否已加载的示例脚本,因为您无法方便地使用 $(document).ready(function...

http://neighborhood.org/core/sample/jquery/append-to-head.htm

【讨论】:

  • script.onload = function() { alert('jQuery loaded!'); } 怎么样?这行得通吗?
【解决方案3】:

方法一:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

方法二:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

如果 jquery.js 文件没有加载,我们可以像这样强制加载它:

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

【讨论】:

    【解决方案4】:

    试试这个:

    <script>
      window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
    </script>
    

    这会检查 jQuery 是否可用,如果不可用,它将从指定的路径动态添加一个。

    参考:Simulate an "include_once" for jQuery

    include_once 等效于 js。参考:https://raw.github.com/kvz/phpjs/master/functions/language/include_once.js

    function include_once (filename) {
      // http://kevin.vanzonneveld.net
      // +   original by: Legaev Andrey
      // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +   improved by: Michael White (http://getsprink.com)
      // +      input by: Brett Zamir (http://brett-zamir.me)
      // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
      // -    depends on: include
      // %        note 1: Uses global: php_js to keep track of included files (though private static variable in namespaced version)
      // *     example 1: include_once('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
      // *     returns 1: true
      var cur_file = {};
      cur_file[this.window.location.href] = 1;
    
      // BEGIN STATIC
      try { // We can't try to access on window, since it might not exist in some environments, and if we use "this.window"
        //    we risk adding another copy if different window objects are associated with the namespaced object
        php_js_shared; // Will be private static variable in namespaced version or global in non-namespaced
        //   version since we wish to share this across all instances
      } catch (e) {
        php_js_shared = {};
      }
      // END STATIC
      if (!php_js_shared.includes) {
        php_js_shared.includes = cur_file;
      }
      if (!php_js_shared.includes[filename]) {
        if (this.include(filename)) {
          return true;
        }
      } else {
        return true;
      }
      return false;
    }
    

    【讨论】:

      【解决方案5】:

      即使您可能附加了头部,它也可能不适用于所有浏览器。这是我发现唯一有效的方法。

      <script type="text/javascript">
      if (typeof jQuery == 'undefined') {
        document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"><\/script>');        
        } 
      </script>
      

      【讨论】:

      • document.write 不是 高度 皱眉吗?
      【解决方案6】:

      您可以通过多种方式检查 jQuery 是否已加载,例如:

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


      if (typeof jQuery == 'function')
      //or
      if (typeof $== 'function')
      


      if (jQuery) {
          // This will throw an error in STRICT MODE if jQuery is not loaded, so don't use if using strict mode
          alert("jquery is loaded");
      } else {
          alert("Not loaded");
      }
      


      if( 'jQuery' in window ) {
          // Do Stuff
      }
      

      现在检查是否未加载 jQuery 后,您可以像这样加载 jQuery:

      虽然这部分已经在这篇文章中得到了很多人的回答,但仍然 为了代码的完整性而回答


          // This part should be inside your IF condition when you do not find jQuery loaded
          var script = document.createElement('script');
          script.type = "text/javascript";
          script.src = "http://code.jquery.com/jquery-3.3.1.min.js";
          document.getElementsByTagName('head')[0].appendChild(script);
      

      【讨论】:

        【解决方案7】:

        旧帖子,但我提出了一个很好的解决方案,在多个地方进行了测试。

        https://github.com/CreativForm/Load-jQuery-if-it-is-not-already-loaded

        代码:

        (function(url, position, callback){
            // default values
            url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
            position = position || 0;
        
            // Check is jQuery exists
            if (!window.jQuery) {
                // Initialize <head>
                var head = document.getElementsByTagName('head')[0];
                // Create <script> element
                var script = document.createElement("script");
                // Append URL
                script.src = url;
                // Append type
                script.type = 'text/javascript';
                // Append script to <head>
                head.appendChild(script);
                // Move script on proper position
                head.insertBefore(script,head.childNodes[position]);
        
                script.onload = function(){
                    if(typeof callback == 'function') {
                        callback(jQuery);
                    }
                };
            } else {
                if(typeof callback == 'function') {
                    callback(jQuery);
                }
            }
        }('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){ 
            console.log($);
        }));
        

        在 GitHub 上有更好的解释,但一般来说,您可以在 HTML 代码中的任何位置添加此功能,如果尚未加载,您将初始化 jquery。

        【讨论】:

          【解决方案8】:
          var f = ()=>{
              if (!window.jQuery) {
                  var e = document.createElement('script');
                  e.src = "https://code.jquery.com/jquery-3.2.1.min.js";
                  e.onload = function () {
                      jQuery.noConflict();
                      console.log('jQuery ' + jQuery.fn.jquery + ' injected.');
                  };
                  document.head.appendChild(e);
              } else {
                  console.log('jQuery ' + jQuery.fn.jquery + '');
              }
          };
          f();
          

          【讨论】:

          • 你必须在你的代码上添加一些注释来解释它。
          【解决方案9】:
          <script>
          if (typeof(jQuery) == 'undefined'){
                  document.write('<scr' + 'ipt type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></scr' + 'ipt>');
          }
          </script>
          

          【讨论】:

            【解决方案10】:

            我在我的项目中使用 CDN,作为后备处理的一部分,我使用以下代码,

            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
                <script type="text/javascript">
                            if ((typeof jQuery == 'undefined')) {
                                document.write(unescape("%3Cscript src='/Responsive/Scripts/jquery-1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));   
                            }
            </script>
            

            只是为了验证,我删除了 CDN 引用并执行代码。它坏了,它从来没有进入 if 循环,因为 typeof jQuery 是作为 function 而不是 undefined 。

            这是因为缓存的旧版本的 jquery 1.6.1 返回 function 并破坏我的代码,因为我使用的是 jquery 1.9.1。由于我需要确切版本的 jquery,我修改了如下代码,

            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
            <script type="text/javascript">
                        if ((typeof jQuery == 'undefined') || (jQuery.fn.jquery != "1.9.1")) {
                            document.write(unescape("%3Cscript src='/Responsive/Scripts/jquery-1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));   
                        }
            </script>
            

            【讨论】:

              猜你喜欢
              • 2012-07-03
              • 1970-01-01
              • 1970-01-01
              • 2018-08-22
              • 2013-09-08
              • 2011-08-29
              • 2020-06-14
              • 2017-12-30
              • 1970-01-01
              相关资源
              最近更新 更多