Three helpful javascript tips for beginners
I recently started to work with HTML5 and this made me do some research concering Javascript. Since what interests me the most is speed and performance, I am not using a framework but working directly with vanilla javascript.
Before I begin, consider this a sort of disclaimer: I am still rather new in the JavaScript world and I have yet to learn anything. The tips I am about to present are a small sum of what I discovered while reading more savvy sources and should not be considered perls of wisdom from an experienced js dev.
Cache your document instead of accessing it directly
Even though you might not believe it (as I originally had), accessing the DOM document object trough a cached variable is faster than doing it directly. You can convince yourself with this test I made on jsPerf. So you should consider doing something like this in the future:
var doc = document;
myDiv = doc.getElementById('divId');
If you use getElementById a lot, use a function for it
I found this tip on Dustin Diaz's blog, on an older but still useful post and it turned out really handy. I ended up following his advice and using the following function (pretty much the same function made by Dustin, but using the cached document)
function get(elem) {
return doc.getElementById(elem);
}
Not only it saved me a lot of time by reducing the code I had to write, but it can also help by reducing the size of your javascript file. After all, what do you prefer?
myDiv = doc.getElementById('id');
or
myDiv = get('id');
Make as little changes to the DOM as possible
Modifying the page with javascript is a given with the modern websites and sometimes a programmer can forget to optimize his code. I know that for a fact, I've done it myself many times in the past.
And just how can you speed up your code by accessing the DOM less?
Let's say you want to generate a list with 10 items and you do something like this:
myDiv.innerHTML = '<ul>';
for (i = 0; i <= 10; i++) {
myDiv.innerHTML += '<li>' + i + '</li>';
}
So you are accessing and writing the html page 11 times. Well, what about doing this instead?
myDiv.innerHTML = '<ul>';
for (i = 0; i <= 10; i++) {
myDiv.innerHTML += '<li>' + i + '</li>';
}
myDiv.innerHTML += '</ul>';
Voila! You are now only doing it once.
And since we're speaking about "for", here's another tip: don't do
for (var i = 0; i <= myArray.length; i++)
Doing it like this makes unnecessary calls to the length function. Instead, here's a faster solution:
for (var i = 0, len = myArray.length; i <= len; i++)
And there you have it!
I'll post some other useful info on this subject as my learning continues. Until then, feel free to leave me a comment!