Jeff
Jeff

Reputation: 12183

How can I load jQuery if it is not already loaded?

I have a initializor.js that contains the following:

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 isn't, adds it to the Head tag.

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 there a way to do this? Firebug shows the jquery inclusion tag within the head tag!

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

Upvotes: 42

Views: 62700

Answers (6)

aljgom
aljgom

Reputation: 9189

If you're in an async function, you could use await like this:

if(!window.jQuery){
    let 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";
    await script.onload
}
/* Your jQuery code here */

If you're not, you can use (async function(){/*all the code*/})() to wrap and run all the code inside one

.


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

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

Or you could also wrap it in a function to change the order of the code

function runWithJQuery(jQueryCode){
    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;
    }
}
runWithJQuery(function jQueryCode(){
    // your jQuery code
})

Upvotes: 15

Ivijan Stefan Stipić
Ivijan Stefan Stipić

Reputation: 6678

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.

Upvotes: 0

beardhatcode
beardhatcode

Reputation: 4773

To include jQuery you should use this:

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

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

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

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

you could also:

window.jQuery === undefined //true

Upvotes: 36

Fatih Hayrioğlu
Fatih Hayrioğlu

Reputation: 3506

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/

Upvotes: 0

Adam Heath
Adam Heath

Reputation: 4763

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.

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

Upvotes: 57

Steve Elliott
Steve Elliott

Reputation: 659

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.

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

Upvotes: 2

Related Questions