Skip to content

Instantly share code, notes, and snippets.

@johnloy
Created June 10, 2024 18:58
Show Gist options
  • Save johnloy/e700fe038dd8940b3d7fcb5560e7ab97 to your computer and use it in GitHub Desktop.
Save johnloy/e700fe038dd8940b3d7fcb5560e7ab97 to your computer and use it in GitHub Desktop.
Image download progress with XHR
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<progress id='imageProgress' value='0' max='100'></progress>
<img id='myImage' src=''/>
<script>
function GetImageLoader(){
let imageLoader = {};
imageLoader['LoadImage'] = function(imageUrl, progressUpdateCallback){
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', imageUrl, true);
xhr.responseType = 'arraybuffer';
xhr.onprogress = function(e){
if(e.lengthComputable){
progressUpdateCallback(parseInt((e.loaded / e.total) * 100));
}
};
xhr.onloadend = function(){
progressUpdateCallback(100);
var options = {};
var headers = xhr.getAllResponseHeaders();
var typeMatch = headers.match(/^Content-Type\:\s*(.*?)$/mi);
if(typeMatch && typeMatch[1]){
options.type = typeMatch[1];
}
var blob = new Blob([this.response], options);
resolve(window.URL.createObjectURL(blob));
}
xhr.send();
});
}
return imageLoader;
}
let myImage = document.getElementById('myImage');
let imageProgress = document.getElementById('imageProgress');
let imageLoader = GetImageLoader();
function updateProgress(progress){
imageProgress.value = progress;
}
imageLoader.LoadImage('image.jpg', updateProgress)
.then(image => {
myImage.src = image;
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment