views:

34

answers:

1

I am dynamically adding a relatively large number of small images to a page. I make a XMLHTTP request which returns some JSON data of the form

{images:[
  {url:'/image?id=1',
  width:32,
  height:32,
  label:"Foo"},
  {url:'/image?id=2',
  width:32,
  height:32,
  label:"Bar"},
  ....
]}

I then construct some HTML of the form

<ul>
  <li><img src="/image?id=1" width="32" height="32"> Foo</li>
  <li><img src="/image?id=2" width="32" height="32"> Bar</li>
  ...
</ul>

and add that content to the page using the innerHTML property.

The problem is that the content does not seem to appear until all of the images are loaded. Because I am dealing with a relatively large number of images, I would like to see the text content appear first, accompanied by the placeholder images that you might typically see when a browser page is loading. Then as the images are loaded they simply appear in lieu of the placeholders without requiring the entire page to layout again.

I was under the impression that if I specified width/height attributes for the img tag that I would get such placeholders "for free", without having to resort to some complex DHTML/javascript wizardry, but it doesn't seem to work. Is there something I am missing?

+1  A: 

That's strange that they images aren't loading asynchronously. Maybe you could try creating the HTML using DOM functions instead of using innerHTML. For instance (untested):

var ul = document.createElement("ul");
var li = document.createElement("li");
var img = document.createElement("img");
var textNode = document.createTextNode("Foo");

img.src = "/image?id=1";
img.width = 32;
img.height = 32

li.appendChild(img);
li.appendChild(textNode);    
ul.appendChild(li);

document.body.appendChild(ul);

I've done similar things like this with images in the past and they have always worked as expected.

You'd have to use a loop to add each image from the JSON, but you get the idea.

Ash White