I keep reading JS books that contain stuff like:
function onSuccess(entries) {
document.getElementById("loading").innerHTML="";
var ul = document.getElementById("file-listing");
for(var index=0;index<entries.length;index++) {
var li = document.createElement('li');
li.innerHTML = entries[index].name;
ul.appendChild(li);
}
}
However, I read on multiple sites that it’s faster and cleaner to create the whole list in a html = “”, add the ul and li elements and then add the block, append it all in one call… so I am wondering if I should follow the style that I find in many js books or what I read on performance blogs? I am mostly concerned that people reading my code will find it amateurish, if I use the previous code block. Also I have meet a few people that are like, wow all you use is jQuery… instead of using DOM calls like document.getElementById(), etc…
If you mean,
someElement.innerHTML = "HTML tags here";then yes, it’s faster in most cases, because fundamentally parsing and rendering HTML is what browsers do and so they’re very fast at it, whereas if you build things up with DOM calls, there are lots of trips across various layers (JavaScript, DOM, browser internals) each time.But: It also doesn’t matter, in most cases. It can matter if you’re rendering a 2,000-row table with lots of columns; but if you’re not doing that it mostly doesn’t matter. You can optimize if and when you see a problem.
You should do whatever seems cleanest, clearest, and easiest to you.
That’s their problem. 🙂
There’s nothing wrong with using jQuery for all or nearly all of your DOM manipulations; it’s really good at it, and saves you a lot of time and trouble. You should be familiar with the DOM so you can use it when it’s appropriate (jQuery doesn’t do everything; in particular it’s not good at dealing with text nodes), but that doesn’t mean you shouldn’t use jQuery when and where appropriate.
Toward that end, some reading:
…but again, that doesn’t mean you should use it just because someone looks down on using jQuery. Use tools appropriately. The important thing is understanding the tools you’re using (including jQuery, and also the DOM itself), so you can understand when and where to apply them.