I found the following code from a former colleague who is not in our company any more:
var w = window.open('', 'print_window', 'width = 1000, height = 1000');
w.document.write('<html><head><title>Printout</title>' + '<link rel="stylesheet" href="' + document.styleSheets[0].href + '"></head><body>');
w.document.write(modal.dom.root.innerHTML);
w.document.write('</body></html>');
setTimeout(function() {
$(w.document.body).find('.modal-print').remove();
w.document.close();
w.focus();
w.print();
w.close();
}, 500);
I want to reduce the amount of setTimeout
calls in our code and wondered why there is a setTimeout
here. I'd love to remove it but I guess there is a reason why it was added in the first place. Does anyone know why it could be there and if it can be removed safely, so the code would look like this?
var w = window.open('', 'print_window', 'width = 1000, height = 1000');
w.document.write('<html><head><title>Printout</title>' + '<link rel="stylesheet" href="' + document.styleSheets[0].href + '"></head><body>');
w.document.write(modal.dom.root.innerHTML);
w.document.write('</body></html>');
$(w.document.body).find('.modal-print').remove();
w.document.close();
w.focus();
w.print();
w.close();
My guess is that he is waiting for the stylesheet to load. So, maybe waiting for the DOM ready or load event would be a good replacement although I don't know if these would be fired after the stylesheet has been added since window.open()
has been called before adding the code to the new window:
Ready event version:
var w = window.open('', 'print_window', 'width = 1000, height = 1000');
w.document.write('<html><head><title>Printout</title>' + '<link rel="stylesheet" href="' + document.styleSheets[0].href + '"></head><body>');
w.document.write(modal.dom.root.innerHTML);
w.document.write('</body></html>');
// Will ready event be fired? If yes, at the right time?
$(w.document).ready(function () {
$(w.document.body).find('.modal-print').remove();
w.document.close();
w.focus();
w.print();
w.close();
});
Version with load event:
var w = window.open('', 'print_window', 'width = 1000, height = 1000');
w.document.write('<html><head><title>Printout</title>' + '<link rel="stylesheet" href="' + document.styleSheets[0].href + '"></head><body>');
w.document.write(modal.dom.root.innerHTML);
w.document.write('</body></html>');
// Will ready event be fired? If yes, at the right time?
$(w).load(function () {
$(w.document.body).find('.modal-print').remove();
w.document.close();
w.focus();
w.print();
w.close();
});