Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser-independent way to detect when image has been loaded

Tags:

javascript

dom

In IE, you can onreadystatechange. There's onload, but I read scary things. jQuery wraps up the DOM's load event quite nicely with "ready". It seems likely I am just ignorant of another nice library's implementation of image loading.

The context is that I am generating images dynamically (via server callbacks) that can take some time download. In my IE-only code I set the src of the img element, then when the onreadystatechange event fires with the "complete" status, I add it to the DOM so the user sees it.

I'd be happy with a "native" JavaScript solution, or a pointer to a library that does the work. There's so many libraries out there and I'm sure this is a case of me just not knowing about the right one. That said, we're already jQuery users, so I'm not eager to add a very large library just to get this functionality.

like image 632
Sebastian Good Avatar asked May 04 '09 19:05

Sebastian Good


People also ask

How can we detect an image been fully loaded in the browser?

To determine whether an image has been completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can use this with naturalWidth or naturalHeight properties, which would return 0 when the image failed to load.

Which event would occur when document or image is loaded?

Summary. The load event occurs when the document has been completely loaded, including dependent resources like JavaScript files, CSS files, and images. The <img> and <script> elements also support the load event.

What is image loaded?

The image is considered completely loaded if any of the following are true: Neither the src nor the srcset attribute is specified. The srcset attribute is absent and the src attribute, while specified, is the empty string ( "" ). The image resource has been fully fetched and has been queued for rendering/compositing.


2 Answers

NOTE: I wrote this in 2010, the browsers in the wild were IE 8/9 beta, Firefox 3.x, and Chrome 4.x. Please use this for research purposes only, I doubt you could copy/paste this into a modern browser and have it work without issue.

WARNING: It is 2017 now I still get points on this now and then, please only use this for research purposes. I currently have no idea how to detect image loading status, but there are probably much more graceful ways of doing it than this... at least I seriously hope there are. I highly recommend NOT using my code in a production environment without more research.

WARNING Part Two Electric Boogaloo: It is 2019 now, most jQuery functionality is built into vanilla JS now. If you're still using it, it may be time to stop and consider heading over to MDN and reading up on some of the new and fun stuff vanilla JS has to offer.


I'm a bit late to this party, maybe this answer will help someone else...

If you're using jQuery don't bother with the stock event handlers (onclick/onmouseover/etc), actually just stop using them altogether. Use the event methods they provided in their API.


This will alert, before the image is appended to the body, because load event is triggered when the image is loaded into memory. It is doing exactly what you tell it to: create an image with the src of test.jpg, when test.jpg loads do an alert, then append it to the body.

var img = $('<img src="test.jpg" />'); img.load(function() {     alert('Image Loaded'); }); $('body').append(img); 

This will alert, after the image is inserted into the body, again, doing what you told it to: create an image, set an event (no src set, so it hasn't loaded), append the image to the body (still no src), now set the src... now the image is loaded so the event is triggered.

var img = $('<img />'); img.load(function() {     alert('Image Loaded'); }); $('body').append(img); $img.attr('src','test.jpg'); 

You can of course also add an error handler and merge a bunch of events using bind().

var img = $('<img />'); img.bind({     load: function() {         alert('Image loaded.');     },     error: function() {         alert('Error thrown, image didn\'t load, probably a 404.');     } }); $('body').append(img); img.attr('src','test.jpg'); 

Per the request by @ChrisKempen ...

Here is a non-event driven way of determining if the images are broken after the DOM is loaded. This code is a derivative of code from an article by StereoChrome which uses naturalWidth, naturalHeight, and complete attributes to determine if the image exists.

$('img').each(function() {     if (this.naturalWidth === 0 || this.naturalHeight === 0 || this.complete === false) {         alert('broken image');     } }); 
like image 175
Paul J Avatar answered Oct 09 '22 02:10

Paul J


According to the W3C spec, only the BODY and FRAMESET elements provide an "onload" event to attach to. Some browsers support it regardless, but just be aware that it is not required to implement the W3C spec.

Something that might be pertinent to this discussion, though not necessarily the answer you are in need of, is this discussion:

Image.onload event does not fire on Internet Explorer when image is in cache


Something else that may be related to your needs, though it may not, is this info on supporting a synthesized "onload" event for any dynamically-loaded DOM element:

How can I determine if a dynamically-created DOM element has been added to the DOM?

like image 20
Jason Bunting Avatar answered Oct 09 '22 03:10

Jason Bunting