Home  >  Article  >  Web Front-end  >  JavaScript introduces the method of AJAX loading a single picture to display progress

JavaScript introduces the method of AJAX loading a single picture to display progress

coldplay.xixi
coldplay.xixiforward
2021-01-26 10:06:412176browse

JavaScript introduces the method of AJAX loading a single picture to display progress

Free learning recommendation: js video tutorial

Use the Internet on your mobile phone, I often see loading progress bars, especially when loading images.

We have done the loading progress of multiple pictures, but for a single picture, especially when the picture is relatively large, a progress bar is needed to tell the user the loading progress, and it can improve the user experience.

Traditional loading will definitely not work. AJAX loading is required. AJAX loading has a special progress event progress.

The specific demo is as follows. Achieve the goal:

Load an image and display the loading percentage progress; after loading is completed, display the image.

HTML structure:

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

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 an image.

Therefore, when accepting 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

Related free learning recommendations: javascript (video)

The above is the detailed content of JavaScript introduces the method of AJAX loading a single picture to display progress. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete