实现说明
除了函数 reveal,文件里再无其他定义。
异步流被 await 线性化,失败处理保持局部。
使用要点
document只存在于浏览器——Node 运行时没有现成的垫片。- 直接运行文件,输出会带上标签,比如
revealed size:、decode rejected:、chart ready to paint——输出的每一行都能指回产生它的那次调用。
常见问题
「img.decode 就绪后再揭示图片」能在裸 Node.js 里跑吗?
不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。
入口签名:async function reveal(url)
核心语句
reveal('/img/hero.avif').catch((err) => {
// decode() rejects on broken sources — no load/error event wiring needed
console.log('decode rejected:', err.constructor.name);
});
await next.decode();
代码示例
// img.decode() resolves only once the pixels are fully ready to paint —
// await it before insertion so no half-decoded frame ever flashes
const slot = document.querySelector('#preview-slot');
async function reveal(url) {
const next = new Image();
next.src = url;
next.alt = 'product preview';
await next.decode();
slot.replaceChildren(next);
next.classList.add('revealed');
console.log('revealed size:', next.naturalWidth + 'x' + next.naturalHeight);
return next;
}
reveal('/img/hero.avif').catch((err) => {
// decode() rejects on broken sources — no load/error event wiring needed
console.log('decode rejected:', err.constructor.name);
});
// decode() also works on images that are already in the document
const inline = document.querySelector('img.chart');
if (inline) {
inline.decode().then(() => console.log('chart ready to paint'));
}