JavaScript loading progress of an image

前端 未结 7 1955
慢半拍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:01

    With this, you add 2 new functions on the Image() object:

     Image.prototype.load = function(url){
            var thisImg = this;
            var xmlHTTP = new XMLHttpRequest();
            xmlHTTP.open('GET', url,true);
            xmlHTTP.responseType = 'arraybuffer';
            xmlHTTP.onload = function(e) {
                var blob = new Blob([this.response]);
                thisImg.src = window.URL.createObjectURL(blob);
            };
            xmlHTTP.onprogress = function(e) {
                thisImg.completedPercentage = parseInt((e.loaded / e.total) * 100);
            };
            xmlHTTP.onloadstart = function() {
                thisImg.completedPercentage = 0;
            };
            xmlHTTP.send();
        };
    
        Image.prototype.completedPercentage = 0;
    

    And here you use the load function and append the image on a div.

    var img = new Image();
    img.load("url");
    document.getElementById("myDiv").appendChild(img);
    

    During the loading state you can check the progress percentage using img.completedPercentage.

提交回复
热议问题