手动加载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)
})
}
function getBoot2() {
var xhr = new XMLHttpRequest();
xhr.timeout = 30000;
xhr.responseType = "text";
xhr.open('GET', '/a.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>