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])

Where,

  • 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>
<head>
<title>Jquery ajaxScript Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
   $(document).ready(function() {
      $("button").click(function(event){
          $.getScript('index.js', function(e) {
                            myfunction();
          });
      });
   });
</script>
</head>
<body>
   <p>Click on the button to load JavaScript file:</p>
   <button>Load data</button>
</body>
</html>
  • $(“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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*