jQuery.getScript()
The jQuery.getScript()
method in jQuery is used to load a javascript file from from the server using a GET HTTP request then execute it.
jQuery.getScript()
syntaxjQuery.getScript( url[, success ] )
Parameter | Type | Description |
---|---|---|
url |
String | request url |
success |
Function | callback function that is executed if the request succeeds. |
jQuery.getScript()
exampleThe callback is fired once the script has been loaded but not necessarily executed.
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) { console.log( data ); // Data returned console.log( textStatus ); // Success console.log( jqxhr.status ); // 200 console.log( "Load was performed." ); });
Load and execute test.js
$.getScript("test.js", function(){ alert("Script loaded and executed."); });
Load the official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded.
HTML
<button id="go">» Run</button> <div class="block"></div>
jQuery
jQuery.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); }); });