Tag Archives: AJAX

Javascript performance – writing to innerHTML

Recently I was investigating why the performance of one of my AJAX experiment is so bad.

This page uses a Perl CGI script to query a handful of deals sites for syndication of their deals and puts them together in one big RSS. Then the Javascript part displays the big collection of deals as a list. The list can be then narrowed down based on keywords as they are typed.

Since the big RSS usually contains more than 300 entries, the Javascript that was converting the entries into list items in an unordered list, was taking upto 10-15 seconds to render. This was not very pleasant.

Here’s how that part of the code looked:

  for ( it = 0; it < items.length; it++) {
    var item = items[it];
    var it_title = item.getElementsByTagName('title').item(0).firstChild.data;
    var it_link  = item.getElementsByTagName('link').item(0).firstChild.data;

    this.port.innerHTML += "<li class=" + it_li_class + "><a href=\\"" 
                           + it_link + "\\" target=\\"feedr_win\\">"
                           + it_title + "</a>";
  }

After a few experiments, I found that the assignment to this.port.innerHTML was the one that was most expensive. I modified the code to read:

  var html_str = "";

  for ( it = 0; it < items.length; it++) {
    var item = items[it];
    var it_title = item.getElementsByTagName('title').item(0).firstChild.data;
    var it_link  = item.getElementsByTagName('link').item(0).firstChild.data;

    html_str += "<li class=" + it_li_class + "><a href=\\"" 
             + it_link + "\\" target=\\"feedr_win\\">"
             + it_title + "</a>";
  }
  
  this.port.innerHTML = html_str;

That cut the time to less than a second. More than a 10x-15x performance improvement.

Next time I write something directly into innerHTML from Javascript in a loop, I am going to try and see if I can collect the text first and then write it into innerHTML.

AJAX Finally!

Its been on my to-do list for a while to give AJAX a shot. Finally got some time over last couple of weekends to come up with this feed reader as a learning project:

  • News that matters…
  • Most AJAX tutorials I read on the web were helpful only if one is planning to write a monolithic JavaScript – as against object oriented, reusable code. Most JavaScript tutorials were also pretty superficial when it came to OOP. I found this one by Mike Chambers most useful. May be because his example does almost exactly what I was planning. Thanks Mike!

    All in all, AJAX seems to be a cool and easy new technology to implement interactive content on a website. I am sure things get more and more difficult as you start implementing richer feature set. May be I’ll find out if I add features to the news reader.

    I haven’t tested it a whole lot on IE, I don’t use it much anyway. But it works OK on almost all other browsers I use – Firefox, Camino, Safari – to name a few!