[javascript] Load jQuery with Javascript and use jQuery

I am appending the jQuery library to the dom using:

 var script = document.createElement('script');
 script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
 script.type = 'text/javascript';
 document.getElementsByTagName('head')[0].appendChild(script);

However when I run:

jQuery(document).ready(function(){...

The console reports the error:

Uncaught ReferenceError: jQuery is not defined

How do I load jQuery dynamically as well as use it once it is in the dom?

This question is related to javascript jquery

The answer is


You need to run your code AFTER jQuery finished loading

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 = function(){
    // your jQuery code here
} 

or if you're running it in an async function you could use await in the above code

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";
await script.onload
// your jQuery code here

If you want to check first if jQuery already exists in the page, try this


Using require.js you can do the same thing in a safer way. You can just define your dependency on jquery and then execute the code you want using the dependency when it is loaded without polluting the namespace:

I generally recommend this library for managing all dependencies on Javascript. It's simple and allows for an efficient optimization of resource loading. However there's some precautions you may need to take when using it with JQuery . My favourite way to deal with them is explained in this github repo and reflected by the following code sample:

<title>jQuery+RequireJS Sample Page</title>
   <script src="scripts/require.js"></script>
   <script>
   require({
       baseUrl: 'scripts',
       paths: {
           jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min'
       },
       priority: ['jquery']
    }, ['main']);
    </script>

Encosia's website recommends:

<script type="text/javascript" 
        src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  // You may specify partial version numbers, such as "1" or "1.3",
  //  with the same result. Doing so will automatically load the 
  //  latest version matching that partial revision pattern 
  //  (e.g. 1.3 would load 1.3.2 today and 1 would load 1.7.2).
  google.load("jquery", "1.7.2");

  google.setOnLoadCallback(function() {
    // Place init code here instead of $(document).ready()
  });
</script>

But even he admits that it just doesn't compare to doing the following when it comes to optimal performance:

    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script type="text/javascript"> window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js">\x3C/script>')</script>
    <script type="text/javascript" src="scripts.js"></scripts>
</body>
</html>

From the DevTools console, you can run:

document.getElementsByTagName("head")[0].innerHTML += '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"><\/script>';

Check the available jQuery version at https://code.jquery.com/jquery/.

To check whether it's loaded, see: Checking if jquery is loaded using Javascript.


There is an other way to load jQuery dynamically (source). You could also use

document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>');

It's considered bad practice to use document.write, but for sake of completion it's good to mention it.

See Why is document.write considered a "bad practice"? for the reasons. The pro is that document.write does block your page from loading other assests, so there is no need to create a callback function.


HTML:

<html>
  <head>

  </head>
  <body>

    <div id='status'>jQuery is not loaded yet.</div>
    <input type='button' value='Click here to load it.' onclick='load()' />

  </body>
</html>   

Script:

   <script>

        load = function() {
          load.getScript("jquery-1.7.2.js");
          load.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
        }

        // dynamically load any javascript file.
        load.getScript = function(filename) {
          var script = document.createElement('script')
          script.setAttribute("type","text/javascript")
          script.setAttribute("src", filename)
          if (typeof script!="undefined")
          document.getElementsByTagName("head")[0].appendChild(script)
        }

        </script>

The reason you are getting this error is that JavaScript is not waiting for the script to be loaded, so when you run

jQuery(document).ready(function(){...

there is not guarantee that the script is ready (and never will be).

This is not the most elegant solution but its workable. Essentially you can check every 1 second for the jQuery object ad run a function when its loaded with your code in it. I would add a timeout (say clearTimeout after its been run 20 times) as well to stop the check from occurring indefinitely.

var jQueryIsReady = function(){
    //Your JQuery code here
}

var checkJquery = function(){
    if(typeof jQuery === "undefined"){
        return false;
    }else{
        clearTimeout(interval);
        jQueryIsReady();
    }
}
var interval = setInterval(checkJquery,1000);