JavaScript loading progress of an image

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

    Sebastian's answer is excellent, the best I've seen to this question. There are, however, a few possible improvements. I use his code modified like this:

    Image.prototype.load = function( url, callback ) {
        var thisImg = this,
            xmlHTTP = new XMLHttpRequest();
    
        thisImg.completedPercentage = 0;
    
        xmlHTTP.open( 'GET', url , true );
        xmlHTTP.responseType = 'arraybuffer';
    
        xmlHTTP.onload = function( e ) {
            var h = xmlHTTP.getAllResponseHeaders(),
                m = h.match( /^Content-Type\:\s*(.*?)$/mi ),
                mimeType = m[ 1 ] || 'image/png';
                // Remove your progress bar or whatever here. Load is done.
    
            var blob = new Blob( [ this.response ], { type: mimeType } );
            thisImg.src = window.URL.createObjectURL( blob );
            if ( callback ) callback( this );
        };
    
        xmlHTTP.onprogress = function( e ) {
            if ( e.lengthComputable )
                thisImg.completedPercentage = parseInt( ( e.loaded / e.total ) * 100 );
            // Update your progress bar here. Make sure to check if the progress value
            // has changed to avoid spamming the DOM.
            // Something like: 
            // if ( prevValue != thisImage completedPercentage ) display_progress();
        };
    
        xmlHTTP.onloadstart = function() {
            // Display your progress bar here, starting at 0
            thisImg.completedPercentage = 0;
        };
    
        xmlHTTP.onloadend = function() {
            // You can also remove your progress bar here, if you like.
            thisImg.completedPercentage = 100;
        }
    
        xmlHTTP.send();
    };
    

    Mainly I added a mime-type and some minor details. Use as Sebastian describes. Works well.

    0 讨论(0)
提交回复
热议问题