Javascript speed improvements

May 12th, 2008 | by bryan |

Did some profiling of ReadPath‘s javascript code last week because I was concerned with some slowness during updates when users had 1000’s of subscriptions. When this happens the browser gets back a hash of counts of unread items for the subscriptions. If the count has changed from what the browser has as the count then we need to update the count for that subscription along with possibly the folder count and the total count in two places.

Using Firebug‘s profiling abilities was a huge help here. I was able to run through this code and determine what was causing the slow down. It turns out that on some updates hundreds of points on the page required updating. I was using Prototype‘s methods to update these divs and for all of Prototypes methods there are calls to stripScripts and extractScripts. These methods are incredibly useful when placing full pieces of html into a page, but for my purposes where it’s only simple text being updated, it was a huge overhead.

I considered altering the Prototype library to make these methods switchable with a param as to whether these checks are performed. In the end though, I decided to go with some previous code. This provided an update method that was simpler and faster, but doesn’t handle evaling javascript. So, when I know that the update is only going to be textual I use the replaceText() method instead. This dramatically improved the performance in the browser to the point where updates really aren’t noticeable anymore. And this is definitely a good thing.

function replaceText(element, text) {
var oldElement = (typeof element === “string” ? document.getElementById(element) : element);
var newElement = oldElement.cloneNode(false);
newElement.innerHTML = text;
oldElement.parentNode.replaceChild(newElement, oldElement);
return newElement;
}

 
 
 
 

Post a Comment