5 ways to speedup javascript
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) use settimeout
Browsers run Javascript code synchronously. This means that when a
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.â€
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.
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:
{
var newElement = document.getElementById("myitem");
newElement.innerHTML = ""; // Clear out the previous
newElement.innerHTML += addHeader();
newElement.innerHTML += addBody();
}
<strong>
Here is the optimized function:</strong>
function buildString()
{
var newText = addHeader() + addBody();
document.getElementById("myitem").innerHTML = newText;
}
4 comments
#6 Anytime you introduce a new variable into your code, always use “var” to signify that a variable is new. This will prevent javascript from having to do a global lookup for that variable. It adds a little bit to the size of your javascript file, but it’s worth it! Global lookups are resource expensive.
[...] Read the rest here:Â 5 ways to speedup javascript | A blend of programming and seo [...]
[...] 5 ways to speedup javascript [...]
I would aslo suggest to check out this 5 easy tips on how to improve your jQuery code performance.
And thanks for these tips. Keep up the good work…
Leave a Comment