[Home] [Blog] [Contact] - [Talks] [Bio] [Customers]
twitter linkedin youtube github rss

Patrick Debois

Is your Jquery or Javascript getting Slow or bad Performance ?

Let me first start by saying that JQuery itself is not slow! By using a framework, one often does not see the work that is done behind the scenes. So one simple command can often have a lot of loops or logic in it.

In a recent project, we had an application that had to create more then 1000 elements dynamically at page load (it first read an XML file, parsed by Jquery) and then created the whole DOM structure.

The page would freeze at startup hogging the browser for a few seconds (too many). Also changing information on the same page again required recreating this structure.

The following is a brief summary of what we found and applied as techniques to make it feel less blocking.

Tip 1: Use ID's instead of class selectors (JQuery)

When inserting a lot of dom elements finding an element by a selector f.i. $('.one-element') can become very slow because it has go through the whole DOM structure. The solution is to give as much hints of the location as possible: either by specifying a ('.block1 > .block2 > .block3 ....) or using a direct ID (#block3) .

     To see the difference in speed test : http://www.kenzomedia.com/speedtest/

Tip 2:Filter vs. Find (JQuery)
Sometimes it is better to filter then find.

Tip 3:Strings vs. Array Join (Javascript)

Another debate is to avoid using the string1=string2+string3 but add all strings to a array stringT and then join the array. This depends on your browser to make difference .
    To see the difference:

Tip 4a: Threading: hanging (Javascript)

As much as we would like it, javascript is not multithreaded !

That means that when you f.i. insert a lot of elements, it often will not get rendered before the browser gets some breathing space. So you have to split your adding elements loop in small batches and then allow the browser some time and then insert the next batch. This can be done using the setTimeout technique to schedule the next add in a few milliseconds. This is also the reason why your elements will show up when you do an alert (because the browser takes control again) and not when doing it in a for loop.

Tip 4b: Generators vs. Iterators

Somewhat related you can use generators instead of iterators

Tip 5: Troubleshooting tools