Last active
August 29, 2015 13:56
-
-
Save elisechant/9184599 to your computer and use it in GitHub Desktop.
Ajax Progess Loader with Deferreds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> | |
</head> | |
<body> | |
Loading <output id="output">0%</output> | |
<br> | |
Loading <progress id="progress" value="0">0%</progress> | |
<script> | |
(function() { | |
function getSource() { | |
var deferred = $.Deferred(); | |
$.ajax({ | |
url: 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.countries%20where%20place%3D%22North%20America%22&format=json&diagnostics=true&callback=', | |
success: deferred.resolve, | |
error: deferred.reject, | |
xhrFields: { | |
onprogress: function (e) { | |
if (e.lengthComputable) { | |
deferred.notify(parseInt(e.loaded / e.total * 100), 10); | |
} | |
} | |
} | |
}); | |
return deferred.promise(); | |
} | |
$.when( | |
getSource() | |
).then( | |
function(json) { | |
console.log('success ' + json); | |
}, | |
function() { | |
console.log('error'); | |
}, | |
function(value) { | |
$('#output').text(value + "%"); | |
$('#progress').attr('value', value); | |
} | |
) | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment