How to use jQuery.getScript() method to load external js files?


The jQuery.getScript( url, [callback] ) method loads and executes a JavaScript file using an HTTP GET request.

Here is the description of all the parameters used by this method −

  • url − A string containing the URL to which the request is sent
  • callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.

Assuming we have following JavaScript content in result.js file −

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

Example

The following is the code snippet showing the usage of this method −

<head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               $.getScript('result.js', function(jd) {
                  // Call custom function defined in script
                  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 = "driver" value = "Load Data" />
       
   </body>

Updated on: 17-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements