I have been tasked with developing an MVC C# application where the contents of a div are dynamically created using an AJAX call to fetch data from a database. Upon successful retrieval, the content is then displayed as a success message in JavaScript. Here's a simple example of the generated string:
"<div style='background:yellow'>asdf<img src='myfile.jpg'></div>"
To print this content, the following function is used:
function printDivContents(contents) {
var printContents = contents;
var originalContents = document.body.innerHTML;
document.body.innerHTML = "<div style='margin:10px'>" + printContents + "</div>";
window.print();
document.body.innerHTML = originalContents;
}
While everything prints correctly most of the time, there seems to be an issue with the image within the content only printing if it has been loaded before. I am looking for a solution to ensure that the image always prints, regardless of prior loading. I have experimented with preloading the script into the content string but have not had success thus far. It is important to note that I can only use pure JavaScript and inline CSS exclusively. What options do I have to address this issue? Should I halt execution to wait for the DOM to load, set the image as a hidden div background on the calling page, or pursue another approach?