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


117

有谁知道如何检查是否已加载jQuery(使用JavaScript),然后再加载(如果尚未加载)。

就像是

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

1
感谢您的注意!希望它实际上不再需要被调用。只是试图增加一点冗余
十七

Answers:


166

也许是这样的:

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

5
请注意,这假设文档具有head可以将脚本元素附加到
Daniel LeCheminant

1
@DanielLeCheminant的观点很不错。如果是的话( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( script );
pawelglow 2012年

3
@Pawel我已经看到一些实现在第一个脚本标记之前/之后插入元素,因为您知道其中必须有一个。
Daniel LeCheminant 2012年

我相信将script标记附加到body可以在所有浏览器中使用。
史蒂文·卢

3
因此,总而言之;最安全的方法是:(document.getElementsByTagName('head')[0] || document.getElementsByTagName('script')[0]).appendChild(script); 由于将至少存在一个脚本标签实例。
tormuto

106

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

而是使用:if(jQuery的typeof =='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


script.onload = function() { alert('jQuery loaded!'); }呢 那行得通吗?
robsch

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

8

试试这个 :

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

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

参考:模拟jQuery的“ include_once”

要么

等效于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;
}

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>

2
是不是document.write HIGHLY令人难以接受的?
Carcigenicate

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

1

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

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,则可以对其进行初始化。


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

您必须在代码上添加一些注释以进行解释。
易卜拉欣Poursadeqi

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>

-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参考并执行代码。它是坏掉的,如果作为typeof jQuery的循环作为函数而不是undefined 进入,则永远不会进入。

这是因为缓存的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>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.