How to include multiple js files using jQuery $.getScript() method?


To use multiple js files, use the same getScript(), which is used to add a single js file. We’re having result.js file with the following code snippet −

function CheckJS(){
   alert("This is JavaScript - File1");
}

We’re having result2.js file with the following code snippet −

function CheckJS(){
   alert("This is JavaScript – File2");
}

Example

Here's the code snippet to add multiple js files. Here, we will call the function in the above 2 js files −

   <head>

      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#button1").click(function(event){
               $.getScript('result.js', function(jd) {
                  // Call custom function defined in script 1
                  CheckJS();
               });
            });
   
           $("#button2").click(function(event){
               $.getScript('result2.js', function(jd) {
                  // Call custom function defined in script 2
                  CheckJS();
               });
            });
               
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.js file −</p>
       
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
       
      <input type = "button" id = "button1" value = "Load Data" />
      <input type = "button" id = "button2" value = "Load 2 Data" />
       
   </body>

Updated on: 17-Feb-2020

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements