2

After an issue with the CSS not working when using the print() method, I was given the answer here that it's because it takes time for the CSS files to load, and it was correct.

So now I have an arbitrary timeout set to let the CSS files load:

<script>
let printData = '';
printData += '<head><link rel="stylesheet" href="mystylesheet.css" type="text/css" /></head>';
printData += '<body><p id="test">Hello</p></body>'

let printWindow = window.open('', 'Print', 'height=600,width=800');
printWindow.document.write(printData);
printWindow.document.close();
printWindow.focus();

function myprint() {
    printWindow.print();
    printWindow.close();
}

setTimeout(myprint,  1000)
</script>

But instead of waiting too much (or too little) by giving some arbitrary time, is there a way to update the code such that it will launch the print screen as soon as everything finishes loading?

3
  • 2
    Did you try the onload event? Commented Apr 20, 2023 at 8:18
  • 1
    Have you tried to attach a onload eventlistener to the printWindow body ? Commented Apr 20, 2023 at 8:18
  • No however I did see this post: stackoverflow.com/questions/68435166/…, but it's a bit different because I have a single write(), so wasn't sure how to place it here. Should I just add a separate write() for the CSS links with onload as seen in this post? Commented Apr 20, 2023 at 9:07

1 Answer 1

0

call myPrint() in $( document ).ready() method

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.