5 ways to speedup javascript
by Justin Silverton
1) use a compressor
JSMin is a filter which removes comments and unnecessary whitespace from JavaScript files. It typically reduces filesize by half, resulting in faster downloads. It also encourages a more expressive programming style because it eliminates the download cost of clean, literate self-documentation.
PHP version here
2) Minimize the number of .js files
Each .js file reference on a web page means another http request from a client’s browser. Although it may decrease the readability/maintainability of your code, it is faster to have one larger .js file than multiple smaller ones.
3) use profiler and timer tools
Firebug offers a suite of profiler and timing tools that allows you to see exactly how long your scripts take to execute and gives you the ability to tweak and optimize them.
4) asynchronize your code
Browsers run Javascript code synchronously. This means that when a <script> tag has been found, everything on the page stops until the end script tag has been found. If a script doesn’t finish executing within a certain amount of time, then the user gets a warning that says, “A script on this page is taking a long time to complete.”
example:
function testfunc()
{
var x1="test1";
var x2="test2";
alert(x1+x2);
}
testfunc(); //normal way to execute the function
window.setTimeout(testfunc,0); //asynchronous execution of testfunc()
The setTimeout function takes 2 parameters. The first is the name of the function that will be executed and the second is the number of milliseconds to wait until it is called. Since 0 is used for the second parameter, the function is called immediately (it will be forked in the background and the rest of your page will continue to load). This is useful for functions that take a long time to load.
5) cache DOM variables
Every binding in Javascript is late. This means each time you access a property, variable, or method a look-up is performed. Within the IE DOM, this could mean an extensive search of the element to find the same property over and over again, only to be returned to the JScript engine unchanged from the previous request.
Here is an example of a function that can be optimized:
function buildString()
{
var newElement = document.getElementById("myitem");
newElement.innerHTML = ""; // Clear out the previous
newElement.innerHTML += addHeader();
newElement.innerHTML += addBody();
}
Here is the optimized function:
function buildString()
{
var newText = addHeader() + addBody();
document.getElementById(”myitem”).innerHTML = newText;
}
9 Comments so far
Leave a reply






I have a question about the fifth.
How about
document.getElementById("myitem").innerHTML = addHeader() + addBody();? It seems like easier :p[…] Under overskriften: 5 ways to speedup javascript: 1) use a compressor, 2) Minimize the number of .js files, 3) use profiler and timer tools, 4) asynchronize your code, 5) cache DOM variables. Alt med forklaring og eksempler i teksten. […]
The first three points are pretty general and could be applied on anything (like images or stylesheets). But I do not get the last two points. The code is fine, but the description does not correspond to it.
4: The function call won’t be forked on background, it will only be delayed.
5: The optimized function is not faster because of variable lookup. The real reason is that in the first function you were replacing HTML three times, which forced the browser to re-render the element. Optimized function sets the innerHTML property only once, which results in a faster execution.
“4: The function call won’t be forked on background, it will only be delayed.”
it’s not just delayed. If this was the case, execution would be blocked on a page until the function was finished executing. It may not be a direct fork(), but the a function executed with settimeout() is executed by another thread of execution (at least in firefox and IE).
try it out for yourself. use javascript to run a function that will take a long time do execute directly and then use settimeout(’yourfunction()’,0).
JavaScript has no threads, so it is definitely not forked. If you use setTimeout to schedule two function calls in the same time, they will never be executed in parallel - there is nothing asynchronous in it.
The code in script element is executed immediately as it occurs in the HTML. The rendering engine has to wait until the script execution finishes. If you use setTimeout, the function call will be executed later, which allows the rendering engine to continue.
I had a few thoughts about (4):
another solution is continuations:
http://marijn.haverbeke.nl/cps/
Los, it is true that ’setTimeout’ is not a true fork, because JavaScript is single threaded, however it behaves like one. Using setTimeouts during the page initialization will allow the page to finish loading even if JavaScript is still running.
Also, I would use setTimeout of ‘1′ instead of ‘0′, because some ‘A’ browsers don’t handle ‘0′ properly.
[…] การเรียกใช้ DOM variable ที่ดี function buildString(){ var newText = addHeader() + addBody(); document.getElementById(”myitem”).innerHTML = newText; } ———————————————————————————————– ที่มา : http://www.whenpenguinsattack.com/2007/08/20/5-ways-to-speedup-javascript/ […]
[…] Vi ho detto ieri, che sto riscrivendo il vista gadget per mondozune. Alla fine non sono riuscito ad integrare la funionalità Flyout e mi sono limitato solamente a fare una grafica molto più accattivante ed ho OTTIMIZZATO il codice javascritp. L’ illuminazione l’ ho avuta leggendo questo post che ho trovato per caso mentre facevo altre ricerche. […]
[…] 5 Wege Javascript zu beschleunigen […]