tags:

views:

2424

answers:

7

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.

+1  A: 

If im not mistaken in javascript an image tag has the events onload and onerror

here is an intersting bit of code i did to hide broken images

in a style tag

img.failed{
   display:none;
}

using the img onerror i had a piece of javascript that did this.className=failed and it would hide the image if it errored

however i may have misunderstood what your goal

Jim
Although a few browsers support it, the "onload" event is not supported by the W3C standard, and thus not all browsers need to or have to support this.
Jason Bunting
+3  A: 

The only reliable way I've found is to do it all on the client-side like this...

var img = new Image();
img.onload = function() {
  alert('Done!');
}
img.src = '/images/myImage.jpg';
Josh Stodola
Although a few browsers support it, the "onload" event is not supported by the W3C standard, and thus not all browsers need to or have to support this.
Jason Bunting
+1  A: 

I think onload should work fine. Do you have to generate the markup for the images, or can you add them statically? If the latter, I'd suggest the following:

<img src="foo.png" class="classNeededToHideImage" onload="makeVisible(this)">

Alternatively, you can use window.onload to make all images visible at once - window.onload fires after all external ressources have finished loading.

If you want to add the images dynamically, you first have to wait for the DOM to be ready to be modified, ie use jQuery or implement your own DOMContentLoaded hack for browsers which don't support it natively.

Then, you create your image objects, assign onload listeners to make them visible and/or add them to the document.

Even better (but slightly more complicated) would be to create and start loading the images immediately when the script executes. On DOMContentLoaded, you'll have to check each image for complete to decide whether to add them immediately to the document or wait for the image's onload listener to fire.

Christoph
Although a few browsers support it, the "onload" event is not supported by the W3C standard, and thus not all browsers need to or have to support this.
Jason Bunting
Well, when 'a few browsers' seems to be every mainstream browser sinde NN4, it's reasonably safe to assume that the feature won't go away any time soon. Sad as it may be, the W3C specs seldom reflect the reality web developers face...
Christoph
Again, I am aware of this, but it is always good to note what the specs say, if for no other reason to understand exactly what you point out - that they are out of touch with reality and need to be updated.By the way, what is "js-hacks" and why is it needed? I noticed from your profile that you created it, but it's difficult to discover what it is since your website for it is lacking in information and I don't have time to read through all of the files looking for just that.
Jason Bunting
@Jason: js-hacks is a place to dump standalone scripts so that I can link to up-to-date versions; most of them are basically useless or just-for-fun, but there are also some which are pretty nice to have when you don't want to use a full-blown framework; problem is, I'm too lazy to write documentation, even if some scripts might deserve exposure to a more general public (e.g. http://mercurial.intuxication.org/hg/js-hacks/raw-file/tip/capture.js is pretty nice and changed my approach to event handling...)
Christoph
@Christoph: Ah, okay - I wasn't sure and thought maybe it was a framework of some sort. I am a fond user of MochiKit (been using it heavily for 3 years now) and have started using jQuery in the last 3 months, but I love JavaScript and enjoy learning new things about it, perhaps I will glean something useful from your scripts. Thanks.
Jason Bunting
+2  A: 

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?

Jason Bunting
that might be true, but onload for images is a de-facto standard (it's been availabe since Netscape Navigator 4)
Christoph
Sure, I never said that it wasn't something he could count on, simply making sure he is aware of the spec - ignore the specs at your own peril.
Jason Bunting
the problem with Image.onload you mention is GWT-specific - see http://code.google.com/p/google-web-toolkit/issues/detail?id=863#c5 ; Image.onload has to be set before Image.src to avoid this, which has already been implicitly mentioned by Josh
Christoph
@Christoph - in your myopia you have forgotten two things: 1) I indicated that it might not be "pertinent to this discussion," but more importantly, 2) other people may land on this page some day because they ran into the problem I linked to, and got here because they were searching SO for their specific problem. If I had posted a link to a problem with tuples in erlang, I could see you getting upset, but I feel my comments are relevant.
Jason Bunting
@Jason: I'm not upset or anything, but your answer imo suggests that using onload with images is more problematic than it actually is; linking to a GWT-specific problem when discussing vanilla JS just seems a bit odd to me - it's not a bug, but reasonable and documented behaviour - check the remarks section of http://msdn.microsoft.com/en-us/library/cc197055(VS.85).aspx
Christoph
OK boys, settle down. Since I'm adding the elements to the DOM myself, I'm not as interested in the additional link. I suppose the implication here is that in IE I should use onreadystatechange, and everywhere else I should use onload which, while not standard, is widely supported?
Sebastian Good
@Sebastian - I don't know, at this point I am just having a good time arguing over minutiae with Christoph. :) J/K Personally, unless you really feel strongly about it, I would simply use, if you are already doing so, jQuery to handle things. I didn't quite understand if you were having problems with this solution or just were not sure if you should try it. I would say, try it, test a few browsers with it, and if it works, you are done. Otherwise, just make sure you handle IE differently, but I would keep to jQuery if you are already using it.
Jason Bunting
@Sebastian: yep, nothing wrong with a good argument about a non-issue ;) @Jason: "You fight like a dairy farmer!"
Christoph
@Christoph: "How appropriate. You fight like a cow." :)
Jason Bunting
A: 

It would appear the answer is use onreadystatechange in IE, and onLoad in other browsers. If neither one is available, do something else. onLoad would be preferable, but IE doesn't fire it when loading an image from the cache, as noted in one of the answers below.

Sebastian Good
IE fires onload when loading from cache - you just have to make sure to set `onload` before setting `src`; the problem Jason mentiones is GWT-specific, which is mentioned on the linked page
Christoph
It would appear you're right -- thanks for diving even deeper to the end of the comment chain. Now I need to test it...
Sebastian Good
+1  A: 

Okay, I'll try to summarize the various partial answers here (including mine).

It would appear the answer is to use onload, which is "widely supported" though not officially required according to standards. Note that for IE in particular, you must set onLoad before setting the src attribute or it may not fire onload when loading an image from the cache. This seems like best practice in any case: set up your event handlers before you start firing events. Where onload is not supported, one should assume that the functionality simply isn't available.

Sebastian Good
+1  A: 

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

If you're using jQuery, don't bother with .onclick/.onload/.on(whatever), 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');
paulj