39

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?

bad_coder
  • 5,829
  • 13
  • 26
  • 41
Jeff
  • 11,384
  • 12
  • 77
  • 145

6 Answers6

54

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();
}
Adam Heath
  • 4,361
  • 1
  • 33
  • 50
  • Will try that! add my button onclick handler in there, right? – Jeff Jul 25 '11 at 08:29
  • Yup, and anything that needs jQuery. You would also need to run the code if jQuery is already defined. – Adam Heath Jul 25 '11 at 08:31
  • would that equal to jQuery's onready event? Because we all hear preaches about writing event handlers in the **ready** event, right? – Jeff Jul 25 '11 at 09:26
  • This did it, thanks!! Also, this is the most painless solution of all :) – Jeff Jul 25 '11 at 09:36
  • @luqita Take a look at http://stackoverflow.com/questions/4845762/onload-handler-for-script-tag-in-internet-explorer – Adam Heath Apr 11 '13 at 06:17
33

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
beardhatcode
  • 3,895
  • 1
  • 13
  • 27
  • The js file I am including, will not be included at the top of the page, but rather within a div or something. Cant I use createElement method? – Jeff Jul 25 '11 at 07:58
  • 1
    it should work, but you're not calling it see end of post, I would append it to the body. And you should always load JS on the end of the page (best practice for page speed/rendering) – beardhatcode Jul 25 '11 at 08:15
  • @gar-onn - Why are you doing "==="? Firebug screams at me when I do it. I changed mine to if(typeof jQuery=="undefined") – Jeff Jul 25 '11 at 08:20
  • 1
    Did I miss the memo? Why are you and Steve telling Jeff to use an old version of JQuery? – AlienWebguy Jul 25 '11 at 08:20
  • was an old snipet, cahnged it to the current version – beardhatcode Jul 25 '11 at 08:23
  • I would prefer doing this without any 3rd party libs – Jeff Jul 25 '11 at 08:23
  • it is the same lib, it only loads faster (witch is better), you can also use: http://code.jquery.com/jquery-1.6.2.min.js or an other from this site: http://docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQuery. – beardhatcode Jul 25 '11 at 08:29
  • @gar-onn - I was referring to Stevens method :) – Jeff Jul 25 '11 at 09:30
  • 2
    This one worked great for me! the "\x3C/Script>" portion when closing the script tag was the part that I needed. I tried document.write to write out the script tag, but the "" was detected as a script closing tag even when in quotes. – WWC Aug 21 '14 at 14:11
12

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
})
aljgom
  • 4,765
  • 1
  • 23
  • 22
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.

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');
     }
   }
 }
Steve Elliott
  • 659
  • 5
  • 13
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/

Fatih Hayrioğlu
  • 3,250
  • 1
  • 24
  • 43
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.

Ivijan Stefan Stipić
  • 4,828
  • 5
  • 35
  • 69