如果尚未加载jQuery,我如何加载它?

时间:2023-01-24 18:07:59

I have a initializor.js that contains the following:

我有一个包含以下内容的initializor.js:

if(typeof jQuery=='undefined')
{
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = 'jquery.js';
    headTag.appendChild(jqTag);
}

I am then including that file somewhere on another page. The code checks if jQuery is loaded, and if it isnt, add it to the Head tag.

然后我将该文件包含在另一页的某个地方。代码检查是否加载了jQuery,如果不加载,则将其添加到Head标记。

However, jQuery is not initializing, because in my main document, I have a few events declared just to test this. I also tried writing some jQuery code below the check, and Firebug said "jQuery is undefined". Is tbere a way to do this? Firebug shows the jquery inclusion tag within the head tag!

但是,jQuery没有初始化,因为在我的主文档中,我声明了一些事件来测试它。我也尝试在支票下面编写一些jQuery代码,Firebug说“jQuery未定义”。这是一种方法吗? Firebug在head标签中显示jquery包含标签!

Also, can I dynamically add code into the $(document).ready() event? Or wouldnt it be necessary just to add some Click events to a few elements?

另外,我可以动态地将代码添加到$(document).ready()事件中吗?或者只是将一些Click事件添加到几个元素中?

6 个解决方案

#1


45  

jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>). You would have to add an onload listener to the script (jqTag) to detect when it loads and then run your code.

当您异步加载jQuery时(通过将其附加到),jQuery不会立即可用。您必须向脚本(jqTag)添加一个onload侦听器,以检测它何时加载然后运行您的代码。

e.g.

例如

function myJQueryCode() {
    //Do stuff with jQuery
}

if(typeof jQuery=='undefined') {
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = 'jquery.js';
    jqTag.onload = myJQueryCode;
    headTag.appendChild(jqTag);
} else {
     myJQueryCode();
}

#2


25  

To include jQuery you should use this:

要包含jQuery,您应该使用:

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js">\x3C/script>')</script>

it uses the Google CDN but provides a fallback an has a protocol relative URL.

它使用谷歌CDN,但提供后备和协议相对URL。

Note: Be sure to change the version number to the latest version

注意:请务必将版本号更改为最新版本


if window.jQuery is defined, it will not continue to read the line since it is an or that already contains a true value, if not it wil (document.)write the value
see: theHTML5Boilerplate

如果定义了window.jQuery,它将不会继续读取该行,因为它是一个或已经包含一个真值,如果不是它wil(document。)写入值,请参阅:theHTML5Boilerplate

also: you forgot the quotes, if jQuery is not defined:

还有:你忘记了引号,如果没有定义jQuery:

typeof window.jQuery === "undefined" //true
typeof window.jQuery == undefined //false ,this is wrong

you could also:

你也可以:

window.jQuery === undefined //true

#3


7  

Refactoring Adam Heath's answer (this is more readable IMO). Bottom line, you need to run the jQuery code AFTER jQuery finished loading.

重构Adam Heath的答案(这是更可读的IMO)。最重要的是,你需要在jQuery完成加载后运行jQuery代码。

jQueryCode = function(){
    // your jQuery code
}

if(window.jQuery)  jQueryCode();
else{   
    var script = document.createElement('script'); 
    document.head.appendChild(script);  
    script.type = 'text/javascript';
    script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";

    script.onload = jQueryCode;
}

#4


2  

The YepNope loader can be used to conditionally load scripts, has quite a nice, easy to read syntax, they have an example of just this on their website.

YepNope加载器可以用来有条件地加载脚本,有一个非常好的,易于阅读的语法,他们在他们的网站上有一个这样的例子。

You can get it from their website.

你可以从他们的网站上获取它。

Example taken from their website:

从他们的网站上取的例子:

 yepnope([{
   load: 'http:/­/ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
   complete: function () {
     if (!window.jQuery) {
       yepnope('local/jquery.min.js');
     }
   }
 }

#5


0  

This site code is solved my problem.

这个站点代码解决了我的问题。

function loadjQuery(url, success){
     var script = document.createElement('script');
     script.src = url;
     var head = document.getElementsByTagName('head')[0],
     done = false;
     head.appendChild(script);
     // Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
    if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
         done = true;
         success();
         script.onload = script.onreadystatechange = null;
         head.removeChild(script);        
    }
};
}
 if (typeof jQuery == 'undefined'){

loadjQuery('http://code.jquery.com/jquery-1.10.2.min.js', function() {
        // Write your jQuery Code
       });
 } else { 
  // jQuery was already loaded
 // Write your jQuery Code
 }

http://99webtools.com/blog/load-jquery-if-not-already-loaded/

http://99webtools.com/blog/load-jquery-if-not-already-loaded/

#6


0  

This is old post but I create one workable solution tested on various places.

这是旧帖子,但我创建了一个在各个地方测试的可行解决方案。

Here is the code.

这是代码。

<script type="text/javascript">
    (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($);
    }));
</script>

Explanation you can find HERE.

你可以在这里找到解释。

#1


45  

jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>). You would have to add an onload listener to the script (jqTag) to detect when it loads and then run your code.

当您异步加载jQuery时(通过将其附加到),jQuery不会立即可用。您必须向脚本(jqTag)添加一个onload侦听器,以检测它何时加载然后运行您的代码。

e.g.

例如

function myJQueryCode() {
    //Do stuff with jQuery
}

if(typeof jQuery=='undefined') {
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = 'jquery.js';
    jqTag.onload = myJQueryCode;
    headTag.appendChild(jqTag);
} else {
     myJQueryCode();
}

#2


25  

To include jQuery you should use this:

要包含jQuery,您应该使用:

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js">\x3C/script>')</script>

it uses the Google CDN but provides a fallback an has a protocol relative URL.

它使用谷歌CDN,但提供后备和协议相对URL。

Note: Be sure to change the version number to the latest version

注意:请务必将版本号更改为最新版本


if window.jQuery is defined, it will not continue to read the line since it is an or that already contains a true value, if not it wil (document.)write the value
see: theHTML5Boilerplate

如果定义了window.jQuery,它将不会继续读取该行,因为它是一个或已经包含一个真值,如果不是它wil(document。)写入值,请参阅:theHTML5Boilerplate

also: you forgot the quotes, if jQuery is not defined:

还有:你忘记了引号,如果没有定义jQuery:

typeof window.jQuery === "undefined" //true
typeof window.jQuery == undefined //false ,this is wrong

you could also:

你也可以:

window.jQuery === undefined //true

#3


7  

Refactoring Adam Heath's answer (this is more readable IMO). Bottom line, you need to run the jQuery code AFTER jQuery finished loading.

重构Adam Heath的答案(这是更可读的IMO)。最重要的是,你需要在jQuery完成加载后运行jQuery代码。

jQueryCode = function(){
    // your jQuery code
}

if(window.jQuery)  jQueryCode();
else{   
    var script = document.createElement('script'); 
    document.head.appendChild(script);  
    script.type = 'text/javascript';
    script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";

    script.onload = jQueryCode;
}

#4


2  

The YepNope loader can be used to conditionally load scripts, has quite a nice, easy to read syntax, they have an example of just this on their website.

YepNope加载器可以用来有条件地加载脚本,有一个非常好的,易于阅读的语法,他们在他们的网站上有一个这样的例子。

You can get it from their website.

你可以从他们的网站上获取它。

Example taken from their website:

从他们的网站上取的例子:

 yepnope([{
   load: 'http:/­/ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
   complete: function () {
     if (!window.jQuery) {
       yepnope('local/jquery.min.js');
     }
   }
 }

#5


0  

This site code is solved my problem.

这个站点代码解决了我的问题。

function loadjQuery(url, success){
     var script = document.createElement('script');
     script.src = url;
     var head = document.getElementsByTagName('head')[0],
     done = false;
     head.appendChild(script);
     // Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
    if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
         done = true;
         success();
         script.onload = script.onreadystatechange = null;
         head.removeChild(script);        
    }
};
}
 if (typeof jQuery == 'undefined'){

loadjQuery('http://code.jquery.com/jquery-1.10.2.min.js', function() {
        // Write your jQuery Code
       });
 } else { 
  // jQuery was already loaded
 // Write your jQuery Code
 }

http://99webtools.com/blog/load-jquery-if-not-already-loaded/

http://99webtools.com/blog/load-jquery-if-not-already-loaded/

#6


0  

This is old post but I create one workable solution tested on various places.

这是旧帖子,但我创建了一个在各个地方测试的可行解决方案。

Here is the code.

这是代码。

<script type="text/javascript">
    (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($);
    }));
</script>

Explanation you can find HERE.

你可以在这里找到解释。