Source Code:
(back to article)
Submit
Result:
Report an issue
<body> <div id="progress-bar" style="width: 100%; background-color: #e0e0e0;"> <div id="progress" style="width: 0; height: 20px; background-color: #76c7c0;"></div> </div> <div id="output"></div> <script> function updateProgressBar(received, total) { const progressElement = document.getElementById('progress'); const percentage = (received / total) * 100; progressElement.style.width = percentage + '%'; alert('Percentage updated! Look at the progress bar. It\'s ' + percentage + '%'); } document.addEventListener('DOMContentLoaded', () => { const url = 'https://www.w3docs.com/uploads/media/default/0001/05/dd10c28a7052fb6d2ff13bc403842b797a73ff3b.txt'; const size = 3_900_000; // it's 3.72 MB fetchWithProgress(url, updateProgressBar, size) .then(data => { document.getElementById('output').textContent = 'File content: ' + data.slice(0, 1000) + '...'; }); }); async function fetchWithProgress(url, onProgress, size) { const response = await fetch(url); const reader = response.body.getReader(); let receivedLength = 0; const chunks = []; while (true) { const { done, value } = await reader.read(); if (done) { break; } chunks.push(value); receivedLength += value.length; onProgress(receivedLength, size); } const chunksAll = new Uint8Array(receivedLength); let position = 0; for (let chunk of chunks) { chunksAll.set(chunk, position); position += chunk.length; } const result = new TextDecoder("utf-8").decode(chunksAll); return result; } </script> </body>