Is it possible to bind an onload event to each image, declaring it once? I tried, but can\'t manage to get it working... (this error is thrown: Uncaught
You can't set a handler on the prototype, no.
In fact, I'm not aware of any way to get a proactive notification for image load if you haven't hooked load
on the specific image element, since load
doesn't bubble.
I only two know two ways to implement a general "some image somewhere has loaded" mechanism:
Use a timer loop, which is obviously unsatisfying on multiple levels. But it does function. The actual query (document.getElementsByTagName("img")
) isn't that bad as it returns a reference to the continually updated (live) HTMLCollection
of img
elements, rather than creating a snapshot like querySelectorAll
does. Then you can use Array.prototype
methods on it (directly, to avoid creating an intermediary array, if you like).
Use a mutation observer to watch for new img
elements being added or the src
attribute on existing img
elements changing, then hook up a load
handler if their complete
property isn't true. (You have to be careful with race conditions there; the property can be changed by the browser even while your JavaScript code is running, because your JavaScript code is running on a single UI thread, but the browser is multi-threaded.)