如何在打印之前等待HTML文档加载/呈现(纯JavaScript) [英] How to wait for HTML document to load/render before printing it (plain JavaScript)
问题描述
我正在使用以下代码在新的html页面上打开并打印图像:
I am using this code to open and print image on new html page:
printView(dataUri:string){
var win = window.open();
win.document.write( '<img src="' + dataUri + '">');
win.print();
win.close();
}
以这种方式使用并且图像大于几kB时,打印预览将打开一个空白页,因为调用打印时不会呈现文档.
When used like that and image is larger than few kB, print preview opens a blank page, because document is not rendered when print is invoked.
我(暂时)通过在打印前引入〜200ms延迟引入setTimeout
来解决了这个问题,
I solved that (temporarily) by introducing setTimeout
with ~200ms delay before printing, like this:
setTimeout( () => {
win.print();
win.close();
}, 200);
这有效,但是我知道我应该使用一些DOM/window事件来等待内容加载.但是,哪个?
And this works, but I am aware that I should use some DOM/window event to wait until content is loaded. But which one?
到目前为止我尝试过的事情:
win.document.onload = ()=>{
console.log('event fired'); // never fired
win.print();
win.close();
}
和
win.addEventListener('load', ()=>{
console.log('event fired'); // never fired
win.print();
win.close();
}
我想保留此Vanilla JS,所以请不要将我引向jQuery window.ready.
I would like to keep this Vanilla JS, so please do not refer me to jQuery window.ready.
推荐答案
向图像添加 onload
属性
add an onload
attribute to your image
win.document.write( '<img src="' + dataUri + '" onload="print()">');
从 printView()
remove win.print()
and win.close()
from printView()
并将它们添加到另一个函数print()
and add them into another function print()
print()
.
print()
will be fired when the image is finished loading.
这一次希望它起作用
这篇关于如何在打印之前等待HTML文档加载/呈现(纯JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!