Michael Buffington

Rendering HTML With JS

Sunday, August 13 2006

In the game I’m currently working on I’ve been tinkering with creating Javascript objects for each tile, duplicating, and placing the tiles wherever I need them. This is in preparation for a smarter blitter that does an Ajax call to the server, asking for the squares it needs to fill the current game window.

In theory, making objects seems like the way to go because you’d think it’s the most efficient way – make one thing, then duplicate it, only changing its properties enough so that it appears on the screen in the right place. In practice it renders very slowly.

So far, the most effective approach seems to be to ditch the object creation approach entirely. Instead, I build up a string, then append that string to the HTML element that’s supposed to contain my squares. It looks like this:

function draw_map(tiles) {
for (var i = 0; i < tiles.length; i++) {
x_y = iso_node_to_screen(tiles[i].attributes[‘x_choord’]-x_choord,tiles[i].attributes[‘y_choord’]-y_choord);
insert_string += draw_tile(x_y0,x_y1,tiles[i].attributes[‘x_choord’],tiles[i].attributes[‘y_choord’]);
}
new Insertion.Bottom(‘board’,insert_string);
}

Insertion.Bottom* comes from Prototype and simply adds a string to whatever element I tell it to.

The problem is that even that doesn’t provide instant response. In Firefox, it’s quick, but with Safari there is a flash. It’s worth noting that in my current game, I’ll only grab that entire field of tiles on a new page load – as the user scrolls the window only a single row of squares will be added at any given time – a total of what’ll probably be just 10 new squares.

I’m not quite sure how to get it any faster, but studying these benchmarks might help. Most suggest that using innerHTML is the way to go, so perhaps I can figure out how to write my own version of Insertion.Bottom that’s a bit more efficient.

  • Insertion.Bottom is by far the worst name for a method I think anyone could come up with.