javascript - Browser-independent way to detect when image has been loaded -
In IE, you can onreadystatechange is there onload, but I read the load events of DOM with JQuery "Ready" Wrap up very well It seems that I am just ignorant of the implementation of another good library of image loading.
The context is that I am generating images dynamically (via server callback) that can be downloaded at some time. In my IE-only code, I set the source of the IMG element, then when the on-fiestentibant event fires with "full" status, I add it to the DOM so that the user can see it.
I want to be happy with a "basic" JavaScript solution, or a pointer for a library that works. There are so many libraries and I'm sure it does not know about just one right about me. She said, we are already a jQuery user, so I'm not eager to add a large library to get this functionality.
Note: I wrote it in 2010, IE 8 / 9 Beta, Firefox 3.x, and Chrome 4.x Please use it for research purposes only, I suspect you can copy / paste it into a modern browser and can work without any problems.
I am delaying this party for some time, maybe this reply will help someone else ...
If you are using jQuery then share event Do not bother with handlers (onclick / onsmower / etc), actually stop using them completely, they use the event methods they provide.
Before adding the image to the body, this will warn, because the load event is triggered when the image is loaded into memory. This is actually what you are saying: create an image with the source of test.jpg, when test.jpg loads a warning, add it to the body.
var img = $ ('& lt; img src = "test.jpg" />' '); Img.load (function () {warning ('image load');}); . $ ('Body') (img) attached; This image, after inserting the image in the body, again, is what you have said it to: create an image, set an event (any set Not set, so it is not loaded), add image to body (no source yet), now set up src ... now the image is loaded so that the event is triggered.
var img = $ ('& lt; img / & gt;'); Img.load (function () {warning ('image load');}); . $ ('Body') (img) attached; $ Img.attr ('src', 'test.jpg'); You can also add an error handler and use a bind () to merge a group of events.
var img = $ ('& lt; img / & gt;'); Img.bind ({load: function () {alert ('image loaded.');}, Error: function () {warning ('error thrown, image not loaded, maybe 404.');}}); . $ ('Body') (img) attached; Img.attr ('src', 'test.jpg'); For requests by @ChrisKempen ...
Here is a non-event driven way to break images after the DOM is loaded. This code is derived from the code of the article by which natural wide, natural white and full attributes are determined using whether the image exists or not.
$ ('img'). Each (function () {if (this.naturalWidth === 0 || this.naturalHeight === 0 || this.complete === incorrect) {Warning ('broken image');}});
Comments
Post a Comment