检查是否已加载jquery,如果为false则加载它

时间:2009-12-01 19:13:56

标签: javascript jquery

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

类似

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

10 个答案:

答案 0 :(得分:161)

也许是这样的:

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

答案 1 :(得分:105)

避免使用“if(!jQuery)”,因为IE会返回错误:jQuery是'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附加到标头后检查JQuery是否已加载。否则你将不得不等待window.onload事件,如果页面有图像,则会更慢。这是一个示例脚本,用于检查JQuery文件是否已加载,因为您无法使用$(document).ready(function ...

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

答案 2 :(得分:14)

方法1:

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

方法2:

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

答案 3 :(得分:7)

试试这个:

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

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

参考:Simulate an "include_once" for jQuery

OR

js的include_once等价物。参考: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;
}

答案 4 :(得分:2)

即使你可能有一个头,但它可能无法在所有浏览器中使用。这是我发现一直工作的唯一方法。

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

答案 5 :(得分:1)

您可以通过多种方式检查是否加载了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);

答案 6 :(得分:0)

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

答案 7 :(得分:0)

旧帖子,但我在serval地方测试了一个很好的解决方案。

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

CODE:

(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 :(得分:0)

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

答案 9 :(得分:-1)

我正在为我的项目使用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引用并执行代码。如果类型的jQuery 函数而不是未定义的方式循环,它就会被打破并且永远不会进入。

这是因为缓存的旧版本的jquery 1.6.1返回函数并破坏了我的代码,因为我使用的是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>
相关问题