Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding HTML with Javascript which has <img> tags. How do I tell when the images are loaded

Lets say I have a div, and want to inject into that div some HTML. The HTML will include 1 or more images.

Is there any way with plain JavaScript or jQuery to determine when the images have loaded?

So if I do the following, can you place an event listener onto a single element to tell when the contents, including images, is ready?:

var html = "<p>Some text <img src='image.jpg' /></p><p>Some more text <img src='image2.jpg' /></p>";
$("div.output").html(html);

The images will be different every time so I cannot preload using JavaScript image object.

One method I'm thinking of doing is running through the HTML with regular expressions or jQuery, finding all image URLs, loop through them and preload each with the image object. When all have been preloaded, then inject the HTML into the output div.

like image 938
Fergal Avatar asked Jan 22 '26 02:01

Fergal


1 Answers

Unless you hook up an onload event to each image before it loads and count them up, there's no easy way to tell when they're all loaded.

like image 150
Diodeus - James MacFarlane Avatar answered Jan 24 '26 19:01

Diodeus - James MacFarlane