I have the following code:
const printString = // a long string w/ several base64 encoded images;
const printContainer = document.createElement('div');
printContainer.innerHTML = printString;
document.body.appendChild(printContainer);
window.print();
printString
is a long string with several largeish base64 encoded images included. The string gets set as the innerHTML
of the printContainer
and then the whole thing gets printed.
This works okay, but on the initial load of the page, it apparently takes the browser a moment to render the base64 encoded images and in that time, window.print()
goes ahead and fires, before all the images have actually loaded into the DOM.
That is, window.print()
can fire before .innerHTML
has finished rendering the new element.
If I add a brief delay to the window.print()
, then everything works fine. Like so:
const printString = // a long string w/ several base64 encoded images;
const printContainer = document.createElement('div');
printContainer.innerHTML = printString;
document.body.appendChild(printContainer);
setTimeout(() => {
window.print();
}, 100);
This isn't a great solution, however, and I would really like to find a solution along the lines of "you just wait until .innerHTML()
is actually finished, window.print();
All of this is tested in Chrome, so far.
Any ideas appreciated!
Edit: an answer
This is a modest reworking of @Keith's answer below.
const imgs = document.querySelectorAll('img.images-in-question');
function checkDone() {
if (ready === imgs.length) {
// do stuffs
}
}
function incrementReady(){
ready++;
checkDone();
}
for (const img of imgs) {
if (img.complete) ready++;
else {
img.addEventListener('load', incrementReady);
}
}
checkDone();