JavaScript hands-on skills: AJAX loading single image display progress

It's finally a holiday, and you can do something you like, but you must keep studying.

--------------------------------------------------

When I use a mobile phone to surf the Internet, I often see a loading progress bar, especially for images.

Do the loading progress of too many pictures, but for a single picture, especially when the picture is relatively large, a progress bar is needed to inform the user of the loading progress, and it can improve the user experience.

The traditional loading is definitely not good, you need to use AJAX loading, AJAX loading has a special progress event progress.

The specific demo is as follows. Goals:

Load a picture, and display the progress of the loading percentage; after loading, the picture will be displayed.

HTML structure:

<div id="pro">
    0%
</div>
<div id="box">
    内容加载中。。。
</div>

JavaScript:

let box = document.getElementById("box");
let pro = document.getElementById("pro");
let req = new XMLHttpRequest();
req.open("get","images/1.png" , true);
req.responseType = "blob";   // 加载二进制数据
req.send();

req.addEventListener("progress",function(oEvent){
    if (oEvent.lengthComputable) {
        var percentComplete = oEvent.loaded / oEvent.total * 100;
        pro.innerHTML = percentComplete + "%" ;
    } else {
        // 总大小未知时不能计算进程信息
    }
});
// 加载完毕
req.addEventListener("load",function(oEvent){
    let blob = req.response;    //  不是 responseText
    pro.innerHTML = "图片加载完毕";
    box.innerHTML = `<img src = ${window.URL.createObjectURL(blob)} >`;
});

What needs to be explained here is:

req.responseType = "blob"; 

Set the request data type to blob type. Binary large Object is a larger binary object that can be used to load non-text data. This demo loads a picture.

Therefore, when receiving the returned data, it is not responseText.

window.URL.createObjectURL(blob) will generate the URL path of the object based on the blob object. In this way, you can see the resources represented by the blob (pictures, videos, audios, etc.) in the browser

 

Guess you like

Origin blog.csdn.net/weixin_42703239/article/details/113060300