javascript - 为什么我的网站在每个文件都成功加载后显示加载图标?
问题描述
所以我在学习 JavaScript Promises 并创建了一个网页,显示从目录中的另一个文件派生的文本。它成功加载了站点和所有内容,但问题是即使在站点加载并从其他网页访问数据之后,它仍显示加载图标。我尝试从文件中删除承诺,当我再次访问该网页时,没有加载图标。所以我认为诺言有问题。
- 1.
controller.js
(主 JS 文件)
function myDisplayer(some) {
document.write(some);
}
async function loadController(){
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "controllerDummy.html");
req.onload = function() {
if (req.status == 200) {
myResolve(req.response);
} else {
myReject("File not Found");
}
};
req.send();
});
myDisplayer(await myPromise);
}
loadController()
- 2.
controller.html
(主文件)
<!DOCTYPE html>
<html style="background-color: black;">
<head>
<script type="text/javascript" src="controller.js"></script>
</head>
<body>
</body>
</html>
- 3.
controllerDummy.html
(承诺从中提取响应文本的虚拟文件)
<!DOCTYPE html>
<html style="background-color: black;">
<body>Loading Controller</body>
</html>
如您所见,promise 已加载,但站点仍在加载图标。有什么解决办法吗?这种方式是过时的还是什么?
解决方案
兑现承诺
function myDisplayer(some) {
document.write(some);
}
async function loadController(){
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "controllerDummy.html");
req.onload = function() {
if (req.status == 200) {
myResolve(req.response);
} else {
myReject("File not Found");
}
};
req.send();
});
myPromise.then((result)=>{
myDisplayer(result);
}).catch((error)=>{
//handle error
});
}
loadController()
推荐阅读
- azure-container-service - 如何从逻辑应用在 Azure 容器注册表中进行身份验证
- android - Flutter 中的圆形显示动画相当于什么?
- python - 如何扩展numpy数组
- java - 如何在我的 Java Web 应用程序中访问 Heroku ClearDB?
- java - PersonQueue 不是抽象的,不会覆盖 Queue 中的抽象方法 addLast()
- java - 有没有办法简化这个三元语句?
- php - 为什么 money_format() PHP 函数不格式化数字?
- php - php simplexml 加载字符串 xmlParseCharRef:无效的 xmlChar 值 25
- jquery - $.fn.jquery 在将 jquery 更新为新版本时显示旧版本
- mysql - vb.net 中的查询错误返回不正确的双精度值