From jQuery JavaScript Library
« Back to Ajax
jQuery.getScript( url, [callback] )
Loads, and executes, a local JavaScript file using an HTTP GET request.
Before jQuery 1.2, getScript was only able to load scripts from the same domain as the original page. As of 1.2, you can now load JavaScript files from any domain.
Warning: Safari 2 and older is unable to evaluate scripts in a global context synchronously. If you load functions via getScript, make sure to call them after a delay.
Arguments:| url | String | |
|---|
| The URL of the page to load. |
| callback (Optional) | Function | |
|---|
A function to be executed whenever the data is loaded successfully.
function (data, textStatus) {
// data should be javascript
this; // the options for this ajax request
}
|
Examples:| Name | Type |
We load the new
official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded.
$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
});
});
</script>
<style>.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}</style>
</head>
<body>
<button id="go">» Run</button>
<div class="block"></div>
</body>
</html>
Load the test.js JavaScript file and execute it.
$.getScript("test.js");
Load the test.js JavaScript file and execute it, displaying an alert message when the execution is complete.
$.getScript("test.js", function(){
alert("Script loaded and executed.");
});