This is one the most amazing things things you can do with JQuery and like with all the other JQuery stuff I have been showing you, this is just just as easy to use.
$.getScript( url, [callback] )
What we are going to do is make a simple html document with a button that when clicked loads a file appropriately named “externalscript.js”
Contents of the HTML File
<button>Click to load a script</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getScript("externalscript.js");
});
});
</script>
So to load external script all you have to do is type $.getScript("externalScript.js"); , easy right?
The external script am going to load for this example is just a line of code that executes an annoying alert box, so don’t try this at home alright.
Contents of the external file
alert("Am an exteral script. I ran when you clicked the button!");