jQuery getScript() function is used to load a JavaScript file from the server using a GET HTTP request, then execute it.
Try it Yourself - Copy paste code in Online HTML Editor to see the result
Try it Yourself - Copy paste code in Online HTML Editor to see the result
Description
Load a JavaScript file from the server using a GET HTTP request, then execute it.
Syntax
jQuery.getScript( url [, success ] )
- url - A string containing the URL to which the request is sent.
- success - 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
});
Example 1
Load the official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getScript demo</title>
<style>
.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<button id="go">» Run</button>
<div class="block"></div>
<script>
var url = "https://code.jquery.com/color/jquery.color.js";
$.getScript(url, function() {
$("#go").click(function() {
$(".block")
.animate({
backgroundColor: "rgb(255, 180, 180)"
}, 1000)
.delay(500)
.animate({
backgroundColor: "olive"
}, 1000)
.delay(500)
.animate({
backgroundColor: "#00f"
}, 1000);
});
});
</script>
</body>
</html>
Example 2
Get and run a JavaScript using an AJAX request:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
});
</script>
</head>
<body>
<button>Use Ajax to get and then run a JavaScript</button>
</body>
</html>
Comments
Post a Comment