How to dynamically load JS inside JS ?

Most of the time, we use static import to include all the exports in our script at the beginning. The import happens every time the script is used, whether the module is used or not. Thus, if someone wants to conditionally import certain parts of a module when required, the static import would be of no help.
Thus, given a JavaScript code, we need to find a solution to load other JavaScript modules only when it is required dynamically.

Approach:

  • ES6 provides us with a construct import(), which provides the facility to import a module on demand.
  • import() returns a promise to provide a module object of the requested module.
  • We can utilize the module object for using the various imports.

Syntax:



import("#ModuleSource").then((module)=>{
     //use module object to access any of the imports.
})

Example: Let us say we want to run a script to perform some operation on string depending on the button clicked.
reverseString.mjs:

filter_none

edit
close

play_arrow

link
brightness_4
code

// reverseString.mjs
// module to reverse a given string
  
export function reverseString(str){
  
    return str.split('').reverse().join('');
  
}

chevron_right


isPalindrome.mjs:

filter_none

edit
close

play_arrow

link
brightness_4
code

// isPalindrome.mjs
// module to check whether string is palindrome or not
  
export function isPalindrome(str){
      
    return (str===str.split('').reverse().join(''))
  
}

chevron_right


index.html:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!-- index.html:- contains frontend scripts -->
<!DOCTYPE html>
<html>
  
<head>
    <title>String operations</title>
</head>
  
<body style="text-align:center;">
  
    <h1 style="color:green;">  
            GeeksForGeeks  
        </h1>
  
    <input type="text" 
           id="myString">
  
    <button id="reverse" 
            style="padding: 0.5em 0.5em;">
      Reverse the String !!
  </button>
  
    <button id="palindrome" 
            style="padding: 0.5em 0.5em;">
      Check whether palindrome !!
  </button>
  
    <div id="answer" 
         style="color: green;
                font-size: 2em; 
                padding: 1em;">
  </div>
  
    <!-- Script to perform one of the operations. -->
    <script type="text/javascript">
        var reverseButton = document.getElementById("reverse");
        var palindromeButton = document.getElementById("palindrome");
        
        //module containing the logic to reverse a string.
        var module1 = '/reverseString.mjs'; 
          
        //module containing the logic to check 
        //whether the string is palindrome or not.
        var module2 = '/isPalindrome.mjs'; 
  
        reverseButton.addEventListener("click", () => {
          
            //consuming the value of input
            var str = document.getElementById("myString").value; 
  
            import (module1).then(module => {
  
                document.getElementById("answer").innerHTML = 
                module.reverseString(str);
  
            });
        });
  
        palindromeButton.addEventListener("click", () => {
          
            //consuming the value of input
            var str = document.getElementById("myString").value; 
  
            import (module2).then(module => {
  
                if (module.isPalindrome(str)) {
                    document.getElementById("answer").innerHTML = 
                    "The string is a palindrome";
                } else {
                    document.getElementById("answer").innerHTML = 
                    "The string is not a palindrome";
                }
            });
        });
    </script>
</body>
  
</html>

chevron_right


Output:

Initial display when the page is loaded.

Initial display when the page is loaded.

After clicking the "Reverse the String" Button.

After clicking the “Reverse the String” Button.

After clicking  the "Check whether palindrome!!" button.

After clicking the “Check whether palindrome!!” button.

Note:

  • The modules can be dynamically loaded inside regular scripts also.
  • A local server needs to be set up to avoid cross site origin issue while using ES6 modules.

When to use what?
Dynamic imports are useful when there is some module which is seldom required in the script. This improves the performance at the initial load time. But if any exports are used frequently within a script, then it can cause some lag during execution.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.