Since downloading the source of a JS
and appending it to the DOM
could be quite painful, you normally would use jQuery.getScript(url [, success ])
. But you can't set a progress function on that call.
Lucky for us: https://api.jquery.com/jquery.getscript/
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: "script",
success: success
});
And on an jQuery.ajax()
call we can set a progress function.
We can calculate the progress percentage if the server includes the response size in http headers. Otherwise we can only use the total received bytes at each progress event call.
$.ajax({
url: 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js', // unminified angular is 1.2mb, perfect for demonstration :)
dateType: 'script',
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Download progress
xhr.addEventListener("progress", function(evt){
// do something with progress info
if (evt.lengthComputable) {
// we can calculate the percentage
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
console.log(percentComplete);
} else if (evt.loaded)
// we only know the received amount and not the total amount
console.log('downloaded:',evt.loaded);
}, false);
return xhr;
}
}).done(function( data, textStatus, jqXHR ) {
console.log('finished');
}).fail(function( jqXHR, settings, exception ) {
console.log('could not load');
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>