jump to navigation

Loading Remote/External Javascript Files Using getScript() in syncronous-mode November 3, 2011

Posted by Tournas Dimitrios in JQuery.
trackback

GetScript is a jQuery ajax function that loads a script from your specified url and has an extremely useful callback function for when the script is loaded . It basically gets the contents of the external file using an AJAX request . JQuery’s documentation states that this getScript function is simply a shorthand version of this :

$.ajax({
url: url,
dataType: "script",
success: success
});

The shorthand  jQuery.getScript( url, [callback] )  version simplifies this however , this method loads and executes a JavaScript file using an HTTP GET request .

Here is the description of all the parameters used by this method:

  • url: A string containing the URL to which the request is sent
  • callback:: This optional parameter represents a function to be executed whenever the data is loaded successfully.

Example :

//Assuming we have following JavaScript content in custom.js file:

function getmsg(){
alert("This is my custom external message");
}

//
<html>
<head>
<title>Example message</title>
<script type="text/javascript" 
src="/js/jquery-1.6.1min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#button").click(function(event){
$.getScript('custom.js', function(jd) {
// Call custom function defined in script
getmsg();
});
});
});
</script>
</head>
<body>
<p>Click on the button to load custom.js file:</p>
<div id="stage" style="background-color:blue;">
STAGE
</div>
<input type="button" id="button" value="Get ext-message" />
</body>
</html>


Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s