微信小程序中如何判断img.onload=()=>{}已经执行完
时间: 2024-04-07 21:34:02 浏览: 180
在微信小程序中,可以使用 Promise 和 async/await 的方式来判断图片加载完成。以下是一个示例代码:
```javascript
function imageLoaded(imgUrl) {
return new Promise((resolve, reject) => {
const img = wx.createImage();
img.onload = function() {
resolve();
};
img.onerror = function() {
reject(new Error("图片加载失败"));
};
img.src = imgUrl;
});
}
async function checkImageLoaded() {
const imgUrl = "图片地址";
try {
await imageLoaded(imgUrl);
console.log("图片加载完成");
// 在这里执行你想要的操作,表示图片加载已完成
} catch (error) {
console.error(error);
}
}
checkImageLoaded();
```
在上述代码中,`imageLoaded` 函数返回一个 Promise 对象,用于监听图片的 `onload` 和 `onerror` 事件。当图片加载完成时,Promise 被解决(resolve),表示图片加载成功;当图片加载失败时,Promise 被拒绝(reject),并抛出一个错误。
在 `checkImageLoaded` 函数中,使用 `await imageLoaded(imgUrl)` 来等待图片加载完成。当 Promise 被解决时,即表示图片加载已经完成,可以在函数内部执行相应的操作。
你可以将图片的地址替换为你自己的图片地址。当图片加载完成后,会在控制台输出 "图片加载完成"。
通过使用 Promise 和 async/await 的方式,可以判断图片加载是否已经完成,并在加载完成后执行相应的操作。
阅读全文
相关推荐


















