-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
promise实现图片异步加载 #155
Comments
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
h1 {
display: block;
}
</style>
<body>
<div id="box">
<h1>我是一张缺省图</h1>
</div>
</body>
</html>
<style></style>
<script>
var oBox = document.getElementById("box");
var oH = document.querySelector("h1");
function loadImageAsync(url) {
return new Promise(function (resolve, reject) {
var image = new Image();
image.onload = function () {
resolve(image);
};
image.onerror = function () {
reject(new Error("Could not load image at " + url));
};
image.src = url;
});
}
// 模拟一下异步加载图片
// 用setTimeoutm模拟ajax调用接口,获取接口返回的图片路径,然后传入函数中,函数中已经提前创建好了
// 图片标签。我们在.then的回调函数中自行决定插入div容器中做一些事,比如把缺省图隐藏掉
setTimeout(() => {
loadImageAsync(
"https://img2020.cnblogs.com/blog/2221918/202104/2221918-20210429012928150-1671892053.png"
).then((res) => {
oH.style.display = "none";
oBox.appendChild(res);
});
}, 1000);
</script> |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: