JavaScript loading progress of an image

前端 未结 7 1925
慢半拍i
慢半拍i 2020-11-29 18:55

Is there a way in JS to get the progress of a loading image while the image is being loaded? I want to use the new Progress tag of HTML5 to show the progress of loading imag

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 19:17

    Actually, in latest chrome you can use it.

    $progress = document.querySelector('#progress');
    
    var url = 'https://placekitten.com/g/2000/2000';
    
    var request = new XMLHttpRequest();
    request.onprogress = onProgress;
    request.onload = onComplete;
    request.onerror = onError;
    
    function onProgress(event) {
      if (!event.lengthComputable) {
        return;
      }
      var loaded = event.loaded;
      var total = event.total;
      var progress = (loaded / total).toFixed(2);
    
      $progress.textContent = 'Loading... ' + parseInt(progress * 100) + ' %';
    
      console.log(progress);
    }
    
    function onComplete(event) {
      var $img = document.createElement('img');
      $img.setAttribute('src', url);
      $progress.appendChild($img);
      console.log('complete', url);
    }
    
    function onError(event) {
      console.log('error');
    }
    
    
    $progress.addEventListener('click', function() {
      request.open('GET', url, true);
      request.overrideMimeType('text/plain; charset=x-user-defined');
      request.send(null);
    });
    Click me to load

提交回复
热议问题