Created
June 10, 2024 18:58
-
-
Save johnloy/e700fe038dd8940b3d7fcb5560e7ab97 to your computer and use it in GitHub Desktop.
Image download progress with XHR
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 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