JavaScript loading progress of an image

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.

Leave a Comment