问题
I want to open a new window/tab, put some HTML in the document, then bring up the browser print dialog to print that new window. I am using the following to accomplish this:
var w = window.open();
w.document.write(html);
w.document.close();
Where html contains:
...<body onload="window.print()">...</body>...
This all works, the window pops up, and the print dialog is shown for the new page, however, for some reason the browser isn't waiting for all the images on the page to load before showing the print dialog. It's causing some images not to print.
There are many images, and they are dynamically generated on the server side (takes about 1 sec each to load). How do I force the browser to only print once all the images are loaded?
This happens in Chrome and Firefox that I've confirmed. I appreciate any help.
回答1:
Try putting your printer call in an onload event for the last image.
<img onload="window.print()" ... />
EDIT:
Full answer by OP as seen below:
I came up with the following script using @chockleyc's answer as inspiration. I couldn't just use the last image because they don't necessarily load in order. The following script will print the page after all images have loaded (uses jQuery):
var hasPrinted = false;
$(document).ready(function(){
$('img').load(function(){
var imgs = $('img');
var loadedAll=true;
for(var i=0;i<imgs.length;i++){
loadedAll &= $(imgs[i])[0].complete;
}
if (loadedAll && !hasPrinted) {
console.log('printing');
hasPrinted = true;
window.print();
}
else {
console.log('not all images have loaded');
}
})
});
回答2:
Try changing it from the body.onload event to the window.onload event.
w.window.onload = window.print()
Or something like that.
来源:https://stackoverflow.com/questions/17534415/print-popup-in-javascript-missing-images