JQuery getScript Example

The jQuery getScript() method loads and executes the JavaScript file from remote location using HTTP GET request, then execute it. It is often called as shorthand method for inserting JavaScript into the web page. The main advantage of using getScript is that, it loads content on run time which better than including <script> tag in the head section.

Jquery getScript Syntax

$.getScript ( url,[callback])


  • url: Address to which request is sent.
  • callback: Is the optional callback function, executed when the JavaScript file is loaded successfully.

Jquery getScript Example

To load a JavaScript file, first create a script file and save it with .js extension. Here we have created JavaScript file called ‘index.js’ as shown in the below script.

function myfunction (){
   alert (&quot;JavaScript file is loaded&quot;);

After creating a JavaScript file, write the coding part for the processing of the ajaxgetScript() method and save it with .html extension.

<! DOCTYPE html>
<title>Jquery ajaxScript Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
<script type="text/javascript" language="javascript">
   $(document).ready(function() {
          $.getScript('index.js', function(e) {
   <p>Click on the button to load JavaScript file:</p>
   <button>Load data</button>
  • $(“button”).click(function(event): line defines click event which occurs when button is clicked.
  • $.getScript (‘index.js’, function(e) {myfunction();}: line invokes the JavaScript function i.e. myfunction from the specified file name. When it finds the function, myfunction in the JavaScript file, then getScript method loads the file on the server.
  • After executing the script, we will get alert message saying “JavaScript file is loaded” on the browser.

JQuery getScript Demo

When you run the above example, you would get the following output :

JQuery ajaxgetScript Example1
JQuery ajaxgetScript Example2

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!