Signup/Sign In
LAST UPDATED: JULY 11, 2023

How to Import multiple JavaScript files Dynamically

    Using a script tag in HTML5 is a piece of cake. It can be as simple as using src an attribute with relevant path or URL of JavaScript file.

    <script src="./path/to/script.js"></script>

    However, as size of web projects grow and so the complexity, the number of JavaScript files/modules increase which are used in different features. It can be become overwhelming for the server to serve all files which may not be used by the server.

    One way to solve this problem is to break down your code into smaller and reusable pieces and once you have those pieces that can be served, and loaded when needed. This way, you can reduce load on server and improve performance for users.

    But unlike other languages, plain JavaScript doesn't have a built-in feature for this purpose.

    So, we will discuss some good methods other programmers shared and mostly use:

    1. Appending Script Element with Plain JavaScript
    2. jQuery's function to import scripts
    3. AJAX call with eval

    In this article, learn about some ways to import script.js files dynamically with JavaScript.

    1. Dynamic Script Element using JavaScript

    The idea is to create script elements dynamically and append into <head> tag of HTML document, with script URL as its source attribute.

    Here is how to do it:

    function loadScript(url, callback)
    {
        // add the script element to the head as suggested before
       var head = document.getElementsByTagName('head')[0];
       var script = document.createElement('script');
       script.type = 'text/javascript';
       script.src = url;
    
       // bind the event to the callback function
       script.onreadystatechange = callback;
       script.onload = callback;
    
       // Append script tag in head elemn
       head.appendChild(script);
    }

    Then you write the code you want to use AFTER the script is loaded in a lambda function :

    var myCode = function() {
        // here, use anything defined in the script
    };

    Then you call the function to run all that:

    loadScript("./path/to/script.js", myCode);

    Ok, I got it. But it's a pain to write all this stuff.

    Here is an implementation of above method in Web (HTML, CSS & JS) playground:

    This method has some advantages over the next two:

    • You can load a script from any origin, as long as it is accessible by your browser.
    • You don't need to use eval, which makes your code safer and easier to debug.
    • The code is executed by the browser parser, which can optimize it for performance.
    • You can also import stylesheet or CSS files with this method by changing the 2 lines from loadScript function.

    If you're looking for a jQuery alternative. Well, here we go.

    2. Load JavaScript Files Easily Using jQuery

    As always, when you want to make JavaScript code elegant and simple, you can use jQuery.

    One of the methods is getScript, which does exactly what we want:

    • It loads a script from a URL
    • And executes a callback function when it's done.
    • It also handles cross-browser compatibility and error handling for you.

    Here is how to use it:

    // load the script from the URL and execute a callback function when it's done
    $.getScript("./path/to/script.js", function() {
        // use anything you defined in the above script
        var s = new MySuperObject();
    });

    That's it! Only one line of code does all the work for you. You can also chain multiple calls to getScript if you want to load more than one script.

    3. Import JavaScript Files Using AJAX with eval

    AJAX allows you to send and receive data from a server without reloading the page. You can use AJAX to import JavaScript files from another source and execute them in your web page.

    The basic idea is to use an XMLHttpRequest object to fetch the script from a URL, then use the eval function to execute the code.

    var xhr = new XMLHttpRequest();
    
    // open a GET request to the script URL
    xhr.open("GET", "https://raw.githubusercontent.com/prudhvidendukuri/greetingsInJs/main/script.js");
    
    // set the response type to text
    xhr.responseType = "text";
    
    // define a callback function that runs when the request is done
    xhr.onload = function() {
        // use eval to execute the response text as code
        eval(xhr.responseText);
    
        // now you can use anything you defined in the loaded script
        
    };
    
    // send the request
    xhr.send();
    

    Here is an example of how to do it (Ignore opening and closing script tag):

    This method works, but has major disadvantages:

    • Limited to your domain: Because of the JavaScript safety settings, you can't load a script from a different origin, unless it supports CORS (Cross-Origin Resource Sharing).
    • Eval is bad: It can introduce bugs and security risks. It also makes debugging harder, as the code is not visible in source file or developer tools.
    • The code from the file is executed in the global scope, which can cause conflicts and pollution with other variables and functions.

    Writing all this code can be tedious and repetitive, especially if you want to load multiple scripts. It is recommended to use any of the above two methods.

    I hope you found this article useful and informative. If you have any questions or feedback, please ask at our forum page. Happy Coding!

    Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS