Dynamically Load jQuery Library Using Plain JavaScript

Share this article

This is how you can load the jQuery library using plain JavaScript. As the load takes place asynchronously so i’ve included a callback version too so you know when the script inserted has completed and you can start using jQuery! I previously posted about inserting scripts into secure pages so there are more options for you there too.

Load jQuery library using plain JavaScript

//Load jQuery library using plain JavaScript
(function(){
  var newscript = document.createElement('script');
     newscript.type = 'text/javascript';
     newscript.async = true;
     newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
  (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);
})();

With callback

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

    });


})();

Frequently Asked Questions (FAQs) about Dynamically Loading jQuery Library in JavaScript

What is the purpose of dynamically loading jQuery in JavaScript?

Dynamically loading jQuery in JavaScript is a technique used to load the jQuery library only when it is needed. This can significantly improve the performance of a web page by reducing the initial load time. When a page loads, all scripts linked in the HTML file are loaded as well. If jQuery is not required immediately, loading it dynamically can save bandwidth and speed up the page load time. This technique is particularly useful for websites that use jQuery for specific functionalities rather than the entire site.

How does the dynamic loading of jQuery work?

Dynamic loading of jQuery involves using JavaScript to load the jQuery library only when it’s needed. This is done by creating a new script element, setting its source to the jQuery library URL, and then appending this script element to the HTML document. Once the script is appended, the browser fetches the jQuery library and executes it. This process is usually done inside a function that can be called whenever jQuery is needed.

Can I use jQuery functions immediately after dynamically loading jQuery?

No, you cannot use jQuery functions immediately after dynamically loading jQuery. This is because the browser loads scripts asynchronously. This means that the script continues to load in the background while the rest of your code executes. Therefore, you need to ensure that jQuery is fully loaded before you start using it. This can be done by using a callback function that gets executed once jQuery is loaded.

How can I ensure that jQuery is loaded before using it?

You can ensure that jQuery is loaded before using it by using a callback function. A callback function is a function that is passed as an argument to another function and is executed after the other function has finished executing. In the case of dynamically loading jQuery, you can pass a callback function to the function that loads jQuery. This callback function will contain all the jQuery code and will be executed once jQuery is fully loaded.

What are the benefits of dynamically loading jQuery?

Dynamically loading jQuery has several benefits. First, it can significantly improve the performance of your website by reducing the initial load time. This is because the jQuery library is only loaded when it’s needed, rather than being loaded with the rest of the HTML document. Second, it can save bandwidth, especially for users with slow internet connections. Finally, it can make your code more modular and easier to maintain, as you can load jQuery only for the parts of your website that need it.

Are there any downsides to dynamically loading jQuery?

One potential downside to dynamically loading jQuery is that it can make your code more complex. This is because you need to ensure that jQuery is fully loaded before you start using it, which usually involves using callback functions. However, the benefits of improved performance and reduced bandwidth usage often outweigh this downside.

Can I dynamically load other JavaScript libraries in the same way as jQuery?

Yes, you can dynamically load other JavaScript libraries in the same way as jQuery. The process is the same: create a new script element, set its source to the library’s URL, and append it to the HTML document. This technique can be used with any JavaScript library, not just jQuery.

Can I dynamically load multiple versions of jQuery?

Yes, you can dynamically load multiple versions of jQuery. However, you need to be careful to avoid conflicts between the different versions. jQuery provides a function called noConflict() that can be used to avoid such conflicts. This function gives control of the `= variable back to the first library that implemented it, allowing multiple versions of jQuery to coexist.

Can I use dynamically loaded jQuery with other JavaScript libraries?

Yes, you can use dynamically loaded jQuery with other JavaScript libraries. However, you need to ensure that jQuery is fully loaded before you start using it with other libraries. This can be done by using a callback function that gets executed once jQuery is loaded.

Is dynamically loading jQuery compatible with all browsers?

Dynamically loading jQuery is compatible with all modern browsers that support JavaScript. However, for very old browsers that do not support dynamic script loading, you may need to include jQuery in the HTML document in the traditional way.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

javascript appendChild callbackjQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week