检查jquery是否已加载,如果错误,则加载它。

时间:2021-03-15 07:02:27

Does anyone know how to check if jquery has been loaded (with javascript) then load it if it hasnt been loaded.

是否有人知道如何检查jquery是否已被加载(使用javascript),如果未加载,请加载。

something like

类似的

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

9 个解决方案

#1


147  

Maybe something like this:

也许是这样的:

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

#2


103  

Avoid using "if (!jQuery)" since IE will return the error: jQuery is 'undefined'

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

Instead use: if (typeof 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>

You'll also need to check if the JQuery has loaded after appending it to the header. Otherwise you'll have to wait for the window.onload event, which is slower if the page has images. Here's a sample script which checks if the JQuery file has loaded, since you won't have the convenience of being able to use $(document).ready(function...

您还需要检查在将JQuery附加到header后是否加载了JQuery。否则你就得等窗户了。onload事件,如果页面有图像,则会更慢。这里有一个示例脚本,它检查JQuery文件是否已加载,因为您无法方便地使用$(document).ready(函数…

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

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

#3


12  

Method 1:

方法1:

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

Method 2:

方法2:

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

If jquery.js file is not loaded, we can force load it like so:

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


7  

Try this :

试试这个:

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

This checks if jQuery is available or not, if not it will add one dynamically from path specified.

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

Ref: Simulate an "include_once" for jQuery

Ref:为jQuery模拟一个“include_once”

OR

include_once equivalent for js. Ref: https://raw.github.com/kvz/phpjs/master/functions/language/include_once.js

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

#5


2  

Even though you may have a head appending it may not work in all browsers. This was the only method I found to work consistently.

即使您可能有一个头部附加它可能不会在所有浏览器中工作。这是我发现的唯一能持续工作的方法。

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

#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  

You can check if jQuery is loaded or not by many ways such as:

您可以通过以下方式检查是否加载了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
}

Now after checking if jQuery is not loaded, you can load jQuery like this:

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

Although this part has been answered by many in this post but still answering for the sake of completeness of the code

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


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

#8


0  

Old post but I made an good solution what is tested on serval places.

以前的帖子,但我做了一个很好的解决办法,什么是测试在几个地方。

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

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

At GitHub is better explanation but generaly this function you can add anywhere in your HTML code and you will initialize jquery if is not already loaded.

在GitHub中有更好的解释,但是这个函数可以在HTML代码中添加任何地方,如果还没有加载,就会初始化jquery。

#9


-1  

I am using CDN for my project and as part of fallback handling, i was using below code,

我在项目中使用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>

Just to verify, i removed CDN reference and execute the code. Its broken and it's never entered into if loop as typeof jQuery is coming as function instead of undefined .

为了验证,我删除了CDN引用并执行代码。它是坏的,而且它从来没有进入if循环作为jQuery类型是作为函数而不是未定义的。

This is because of cached older version of jquery 1.6.1 which return function and break my code because i am using jquery 1.9.1. As i need exact version of jquery, i modified code as below,

这是因为缓存的旧版本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>

#1


147  

Maybe something like this:

也许是这样的:

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

#2


103  

Avoid using "if (!jQuery)" since IE will return the error: jQuery is 'undefined'

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

Instead use: if (typeof 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>

You'll also need to check if the JQuery has loaded after appending it to the header. Otherwise you'll have to wait for the window.onload event, which is slower if the page has images. Here's a sample script which checks if the JQuery file has loaded, since you won't have the convenience of being able to use $(document).ready(function...

您还需要检查在将JQuery附加到header后是否加载了JQuery。否则你就得等窗户了。onload事件,如果页面有图像,则会更慢。这里有一个示例脚本,它检查JQuery文件是否已加载,因为您无法方便地使用$(document).ready(函数…

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

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

#3


12  

Method 1:

方法1:

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

Method 2:

方法2:

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

If jquery.js file is not loaded, we can force load it like so:

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


7  

Try this :

试试这个:

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

This checks if jQuery is available or not, if not it will add one dynamically from path specified.

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

Ref: Simulate an "include_once" for jQuery

Ref:为jQuery模拟一个“include_once”

OR

include_once equivalent for js. Ref: https://raw.github.com/kvz/phpjs/master/functions/language/include_once.js

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

#5


2  

Even though you may have a head appending it may not work in all browsers. This was the only method I found to work consistently.

即使您可能有一个头部附加它可能不会在所有浏览器中工作。这是我发现的唯一能持续工作的方法。

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

#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  

You can check if jQuery is loaded or not by many ways such as:

您可以通过以下方式检查是否加载了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
}

Now after checking if jQuery is not loaded, you can load jQuery like this:

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

Although this part has been answered by many in this post but still answering for the sake of completeness of the code

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


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

#8


0  

Old post but I made an good solution what is tested on serval places.

以前的帖子,但我做了一个很好的解决办法,什么是测试在几个地方。

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

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

At GitHub is better explanation but generaly this function you can add anywhere in your HTML code and you will initialize jquery if is not already loaded.

在GitHub中有更好的解释,但是这个函数可以在HTML代码中添加任何地方,如果还没有加载,就会初始化jquery。

#9


-1  

I am using CDN for my project and as part of fallback handling, i was using below code,

我在项目中使用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>

Just to verify, i removed CDN reference and execute the code. Its broken and it's never entered into if loop as typeof jQuery is coming as function instead of undefined .

为了验证,我删除了CDN引用并执行代码。它是坏的,而且它从来没有进入if循环作为jQuery类型是作为函数而不是未定义的。

This is because of cached older version of jquery 1.6.1 which return function and break my code because i am using jquery 1.9.1. As i need exact version of jquery, i modified code as below,

这是因为缓存的旧版本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>