I am trying to make an asynchronous call to a server in the following way
$(document).ready(function(){
$.ajax({
cache: true,
async: true,
dataType: "script",
url:"www.xyz.com/yyy?host_name=abc.com&size=S&use_flash=YES&use_transparent=YES&lang=en",
success: function(data) {
$("#verified").append(data);
console.log("data is "+data);
loading = false;
}
});
});
However the script is not being loaded asynchronously.What exactly am I missing? Any help would be appreciated!
3 Answers 3
Try jQuery.getScript function.
1 Comment
Use Following function for loading javascript asynchronous
function script(url) {
var scriptObject = document.createElement('script');
scriptObject .type = 'text/javascript';
scriptObject .async = true;
scriptObject .src = url;
document.getElementsByTagName('head')[0].appendChild(scriptObject );
}
1 Comment
The "cache" and "async" properties for ajax call have the values "true" by default, you don't have to specify the defaults again.
You mentioned that it takes time for your file to load, that is probably because that the script file you are trying to load is of ample size. By ample size I mean more than 50 or 100 kb.
To reduce the time it takes for your file to load you can minify your js file which will help you reduce the file size of your script and eventually load faster on ajax call.
http://jscompress.com is one of the good on-line minifier available.
Alternatively, you can try using requirejs library which is widely used for loading script files asynchronously. You can download the requirejs library from the following link: http://requirejs.org/docs/download.html
successto retrieve response from the server!