使用Promise实现图片的预加载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsl0530hsl/article/details/88123769

如下是项目的整体结构:
在这里插入图片描述

实现代码如下:

const preLoadImg = function (path) {
    return new Promise(function (resolve, reject) {
        const img = new Image();
        img.onload = resolve;
        img.onerror = reject;
        img.src = path;
    })
};

测试代码如下:

preLoadImg("../../resources/imgs/1.jpg").then(res => {console.log(res, 1);}).catch(e => {console.log(e, 2);});

需要注意的是,Image对象不能单独在JS环境中使用,需要结合 Html 页面一起使用,不然会出如下错误:

ReferenceError: Image is not defined
    at D:\Workspaces\Webstorm\web\javascript\ES6\src\promise\loadImg.js:3:21
    at new Promise (<anonymous>)
    at preLoadImg (D:\Workspaces\Webstorm\web\javascript\ES6\src\promise\loadImg.js:2:12)
    at Object.<anonymous> (D:\Workspaces\Webstorm\web\javascript\ES6\src\promise\loadImg.js:10:1)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)

Process finished with exit code 0

Html中的简单实例如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PreLoad Image</title>
    <script src="loadImg.js"></script>
</head>
<body>
    hello!!
    <img src="../../resources/imgs/1.jpg">
</body>
</html>

猜你喜欢

转载自blog.csdn.net/hsl0530hsl/article/details/88123769