0

Is there a specification for how browsers handle image loading if the image tag is just one of those diembodied Javascript elements that haven't been inserted into the document? An example:

$('<img src="/path/to/image.jpg" />')

Is there a specification that tells the image to load? I ask because I am interested in the following implementation:

  1. Mouseover event on a thumbnail triggers a larger preview image to load.
  2. The larger preview image loads and triggers a load event, at which point it is overlaid on top of the original mouseover element.

The implementation of (2) is not hard, but I want to be sure that I can rely on the load event across browsers. I have tried it in Firebug and the Chrome console and it seems to work fine, but I haven't encountered a specification telling me that it will always work. I wouldn't put it beyond a browser to refuse to load an image that hasn't been placed in document.

Steven
  • 17,796
  • 13
  • 66
  • 118
  • 2
    You're creating the `img` element exactly like that? Not `$('')` first, then setting the `src` attribute? Because they route to fundamentally different things (since jQuery 1.4) which may impact the behavior you are asking about. – Crescent Fresh Jul 28 '10 at 14:24
  • Silly me. I've been doing `$("")` in my code, and I thought I'd be all fancy and shorthand on SO. You make a great point though, and I'm definitely going to keep an eye out for when I inevitably make this mistake in the future. – Steven Jul 28 '10 at 14:45
  • 1
    it seems you have two questions buried in here: 1) does creating a detached `img` element automatically fetch the image's `src` in all browsers? and 2) does the `load` event for an `img` element fire consistently in all browsers? – Crescent Fresh Jul 28 '10 at 15:37

1 Answers1

2

The load event should fire consistently across modern browsers. You may have problems with out-dated browsers (pre-IE6). One thing I must recommend is that you assign a load event handler before setting the src. This ensures the event will fire...

$("<img />").load(function() {
  alert("Loaded!");
  $(this).css("border", "solid 2px black").appendTo("body");  
}).src("/path/to/image.jpg");
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227