Layui 没有 layui.img 模块,图片预加载应使用原生 Image API 实现;单张用 Promise 封装 onload/onerror,多张用 Promise.allSettled 并行处理,注意避坑空值、本地文件误用及 layer.photos 不接受已加载 DOM 元素。

layui.img 并不存在——Layui 官方没有提供名为 layui.img 的模块或方法。你实际想做的,是「预加载远程图片资源(单张或多张),并在全部加载完成或失败后执行回调」,这属于原生浏览器能力范畴,Layui 不封装也不介入。
为什么找不到 layui.img?
Layui 的核心模块列表里没有 img:只有 table、upload、layer、flow 等明确用途的模块。图片预加载不是 UI 组件问题,而是资源加载控制问题,Layui 选择不重复造轮子,交由开发者用标准 DOM API 或轻量逻辑实现。
常见误解来源:
– 把 layui.upload 的 choose 回调中用到的 FileReader 或 URL.createObjectURL 误认为是“layui 图片模块”
– 把 layer.photos 当成加载器(它只负责展示,不负责预加载)
– 在社区帖子里看到自定义的 layui.img = {...} 扩展,误以为是官方 API
怎么预加载单张远程图片(带成功/失败回调)
用 Image 构造函数 + onload/onerror 是最轻量、兼容性最好(IE9+)的方式:
function preloadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error(`Failed to load image: ${src}`));
img.src = src;
});
}
// 使用
preloadImage('https://example.com/avatar.jpg')
.then(img => console.log('加载完成', img.naturalWidth, img.naturalHeight))
.catch(err => console.error(err.message));
- 务必在赋值
img.src前绑定onload/onerror,否则可能错过事件 - 不要依赖
img.complete判断是否已缓存——HTTP 缓存策略下它可能为true,但尺寸等属性尚未就绪 - 如果只是校验 URL 可访问(不真渲染),加载完可立即
img.remove()或丢弃引用
怎么批量预加载多张远程图片并统一回调
用 Promise.allSettled(推荐,保留成功/失败结果)或 Promise.all(任一失败即整体失败):
function preloadImages(sources) {
return Promise.allSettled(
sources.map(src => preloadImage(src))
);
}
// 使用
preloadImages([
'https://example.com/1.jpg',
'https://example.com/2.jpg',
'https://example.com/broken.png'
]).then(results => {
const fulfilled = results.filter(r => r.status === 'fulfilled');
const rejected = results.filter(r => r.status === 'rejected');
console.log(`成功 ${fulfilled.length} 张,失败 ${rejected.length} 张`);
});
- 避免用
for...of+await串行加载——会极大拖慢总耗时 - 如果图片数量很大(>50),建议分批(如每 10 张一组),防止浏览器并发连接数限制或内存压力
- 注意:预加载本身不触发渲染;要显示,仍需把
img插入 DOM 或赋给已有<img>的src
和 Layui 组件配合时的关键避坑点
你在表格头像列、上传预览、layer.photos 之前做预加载,容易踩这些坑:
- 在
table.render().done里对d.avatar预加载,但没过滤空值或about:blank,导致大量onerror触发 - 用
layer.photos({photos: {data: [...]}})传入预加载后的img对象——无效,layer.photos只认src字符串,不接受已加载的 DOM 元素 - 在
upload.choose中对用户选的本地文件调用此逻辑——错,本地文件要用FileReader或URL.createObjectURL,不是new Image() - 预加载后直接
img.src = img.src强制重载——多余,且可能触发二次请求(若服务端没配强缓存)
真正需要预加载的场景其实很窄:比如相册页首屏多图必须「全就绪再显示」,或上传前校验远程封面图有效性。多数时候,懒加载 + 错误占位(onerror="this.src='placeholder.png'")更实用。


















