Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
urlA string containing the URL to which the request is sent.
success(data, textStatus)A callback function that is executed if the request succeeds.
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, dataType: 'script', success: success });
The callback is passed the returned JavaScript file. This is generally not useful as the script will already have run at this point.
The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts should have some impact on the current page:
$('.result').html('<p>Lorem ipsum dolor sit amet.</p>');
The script can then be included and run by referencing the file name:
$.getScript('ajax/test.js', function() { alert('Load was performed.'); });
<!DOCTYPE html>
<html>
<head>
<style>.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}</style>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button id="go">» Run</button>
<div class="block"></div>
<script>$.getScript("https://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
});</script>
</body>
</html>
$.getScript("test.js");
$.getScript("test.js", function(){
alert("Script loaded and executed.");
});