Max Ivak
Max Ivak

Reputation: 1549

Load jQuery dynamically and use it

How to correctly load jQuery library if it is not loaded yet?

somepage.html:

<script src="http://example.com/js/widget_init.js" type="text/javascript"></script>

<script type="text/javascript">
  if (typeof jQuery == 'undefined') {  
    console.log('ERROR: NOT LOADED');
  }
  else{
    console.log('OK');
  }

</script>

The script 'widget_init.js' should load jQuery if it is not loaded yet.

I have this script 'widget_init.js':

function load_script_jquery(){
  if (typeof jQuery == 'undefined') {  
    var jq = document.createElement('script'); jq.type = 'text/javascript';
    jq.src = '/path/to/js/jquery.min.js';
    document.getElementsByTagName('head')[0].appendChild(jq);
  } 
  else {

  }

}

load_script_jquery();

// some other code

The problem is that it doesn't wait for jQuery to be loaded and it shows error like this:

<script type="text/javascript">
  if (typeof jQuery == 'undefined') {  
    console.log('ERROR: NOT LOADED');  // NOT LOADED
  }
  else{
    console.log('OK'); // NEVER GOES HERE
  }

</script>

I tried this also without any effect:

document.write('<script src="/path/to/js/jquery.min.js" type="text/javascript"><\/script>');

How to wait until jQuery is loaded so I can use it ?

Upvotes: 0

Views: 1656

Answers (2)

Manwal
Manwal

Reputation: 23816

You just need callback function, after loading jquery secessfully:

var loadJS = function(url, cb) {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");
        script_tag.setAttribute("src",
            url);
        if (script_tag.readyState) {
            script_tag.onreadystatechange = function() { // For old versions of IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    cb();//calling callback
                }
            };
        } else { // Other browsers
            script_tag.onload = cb;//calling callback function
        }
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    };

And simply call this function with jquery library path and callback function reference:

loadJS(hostUrl + "/js/libraries/jquery.js", callback);

Upvotes: 1

Daniel Ma
Daniel Ma

Reputation: 646

Your code to append the jQuery script will be appended after your <script> snippet that checks for it. That's how .appendChild works

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node

Source: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild (emphasis mine)

Here are two options to solve this:

If you can insert HTML on the page

You can use this snippet from the HTML5 Boilerplate. It will check if another script has already loaded jQuery, and if not, will load it inline.

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

Just drop it in your head or body tag before the script that depends on it.

If you need to dynamically load it in the Javascript source

Follow the instructions in this tutorial

(function () {

    function loadScript(url, callback) {

        var script = document.createElement("script")
        script.type = "text/javascript";

        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { //Others
            script.onload = function () {
                callback();
            };
        }

        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }

    loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {

         //jQuery loaded
         console.log('jquery loaded');

    });


})();

Upvotes: 2

Related Questions