【JavaScript】JS加载JS获取加载进度

手动加载JS并显示JS的加载进度

代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
index
<button onclick="add()">添加</button>
<button onclick="getBoot2()">加载</button>
<script>
    function add() {
    
    
        console.log("添加")
        getBoot().then(res => {
    
    
            console.log("加载结果", res)
        }).catch(error => {
    
    
            console.log("加载失败", error)
        })
    }
	// 直接引入文件加载 没有跨域问题
    function getBoot() {
    
    
        return new Promise((resolve, reject) => {
    
    
            const script = document.createElement("script");
            script.type = "text/javascript";
            script.src = 'http://libs.baidu.com/jquery/2.0.0/jquery.min.js';
            script.onload = resolve;
            script.onerror = reject;
            console.log("script", script)
            document.body.append(script)
        })
    }

	// 读取JS文件加载  和请求接口一样 存在跨域问题
    function getBoot2() {
    
    
        var xhr = new XMLHttpRequest();
        //设置xhr请求的超时时间
        xhr.timeout = 30000;
        //设置响应返回的数据格式
        xhr.responseType = "text";
        //创建一个 post 请求,采用异步
        xhr.open('GET', '/a.js', true);
        // xhr.open('GET', '/b.js', true);
        // 注册相关事件回调处理函数
        xhr.onload = function (e) {
    
    
            if (this.status === 200 || this.status === 304) {
    
    
                console.log(this.responseText);
                const script = document.createElement("script");
                script.type = "text/javascript";
                script.innerHTML = this.responseText
                document.body.append(script)
            }
        };
        xhr.ontimeout = function (e) {
    
    
            console.log("超市", e)
        };
        xhr.onerror = function (e) {
    
    
            console.log("错误", e)
        };
        xhr.onprogress = function (e) {
    
    
            console.log("进度", (e.loaded/e.total*100).toFixed(2) + '%')
        };
        xhr.send();
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/sky529063865/article/details/124152248