jQuery getScript method

Using the method, getScript we can additionally load scripts onto the page. This method accepts the following parameters:

  • url: required parameter containing the address of the script that will be loaded
  • success(script, textStatus, jqXHR): An optional parameter that represents a callback function that will be executed when the request succeeds.

On output, the getScript method returns the jqXHRassociated with the current request.

Suppose we have the following simple redStyle.js script defined on the server :

$('body').css('background-color', 'red');

The script simply colors the page red. Now on the page we will define its loading, for example, by pressing a button:


<button>Download</button>
<script type="text/javascript">
$(function(){
    $('button').click(function(){
        $.getScript('redStyle.js');
    });
});
</script>

Now, after clicking on the button, the script will be loaded and executed, which will color the page in red.