当使用客户端函数填充DOM时,如何等待所有图像从puppeteer中的page.evaluate函数加载



我正在尝试让代码执行等待所有图像加载,然后puppeteer进行屏幕截图。当调用initData((函数时,我的DOM会被填充,该函数在客户端js文件中定义。延迟或超时是一种选择,但我相信一定有更有效的方法

(async (dataObj) => {
const url = dataObj.url;
const payload = dataObj.payload;
const browser = await puppeteer.launch({ headless: false,devtools:false});
const page = await browser.newPage();
await page.goto(url,{'waitUntil': 'networkidle0'});
await page.evaluate((payload) => {
initData(payload);
//initData is a client side function that populates the DOM, need to wait 
//here till the images are loaded. 
},payload)
await page.setViewport({ width: 1280, height: 720 })
await page.screenshot({ path: 'test.png' });
await browser.close();
})(dataObj)

提前谢谢。

如另一个答案中所述,图像元素具有complete属性。您可以编写一个函数,当文档中的所有图像都已提取时返回true:

function imagesHaveLoaded() { return Array.from(document.images).every((i) => i.complete); }

你可以等待这样的功能:

await page.waitForFunction(imagesHaveLoaded);

将两者与原始代码放在一起,并添加一个超时,这样它就不会无限期地等待,我们得到:

function imagesHaveLoaded() {
return Array.from(document.images).every((i) => i.complete);
}
(async (dataObj) => {
const url = dataObj.url;
const payload = dataObj.payload;
const browser = await puppeteer.launch({ headless: false, devtools: false});
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle0' });
await page.evaluate((payload) => {
initData(payload);
}, payload);
await page.waitForFunction(imagesHaveLoaded, { timeout: YOUR_DESIRED_TIMEOUT });
await page.setViewport({ width: 1280, height: 720 })
await page.screenshot({ path: 'test.png' });
await browser.close();
})(dataObj)

您可以使用promise来实现这一点,方法是获取文档上的所有<img>标记并循环检查,直到浏览器获取所有标记(当img.complete == true用于所有img时(,然后解析promise。

HTMLImageElement.complete只读

如果浏览器已完成获取图像(无论是否成功(,则返回一个布尔值,该值为true。如果图像没有src值,它也会显示true。

参考号:MDN HTMLImageElement

我已经为此实现了一个函数,它返回一个promise,该promise在获取所有img时解析,并在超时时拒绝(最初为30秒,但可以更改(。

用法:

// consuming the promise
imgReady().then(
(imgs) => {
// do stuff here
console.log('imgs ready');
},
(err) => {
console.log('imgs taking to long to load');
}
);
// inside asyng functions
const imgs = await imgReady();

关于window.onload的注意事项:您也可以使用window.onload;然而,window.onload等待加载所有内容而不是仅加载图像。

/**
* @param timeout: how long to wait until reject and cancel the execution.
* @param tickrate: how long to recheck all imgs again.
*
* @returns
*   A promise which resolve when all img on document gets fetched.
*   The promise get rejected if it reach the @timeout time to execute.
*/
function imgReady(timeout = 30*1000, tickrate = 10) {
const imgs = Array.from(document.getElementsByTagName('img'));
const t0 = new Date().getTime();
return new Promise((resolve, reject) => {
const checkImg = () => {
const t1 = new Date().getTime();
if (t1 - t0 > timeout) {
reject({
message: `CheckImgReadyTimeoutException: imgs taking to loong to load.`
});
}
if (imgs.every(x => x.complete)) {
resolve(imgs);
} else {
setTimeout(checkImg, tickrate);
}
};
checkImg();
});
}
imgReady().then(console.log,console.error);
img{max-width: 100px;}
<img src="https://upload.wikimedia.org/wikipedia/commons/c/cc/ESC_large_ISS022_ISS022-E-11387-edit_01.JPG">
<br>
<img src="https://www.publicdomainpictures.net/pictures/90000/velka/planet-earth-1401465698wt7.jpg">

最新更新