DOM Element Creation vs. .innerHTML vs. Direct - javascript

When generating dynamic content, which way is better to simply create the HTML and insert it into a .innerHTML or to create elements in the DOM directly?
I'm not concerned with complexity or other. Just processing time on the client.
Which is quicker?
If I had to guess in order of efficiency (low processing time) this would be:
DOM Creation
.innerHTML property insertion
direct writing
This would be inversely related to the complexity of implmenting:
direct writing
.innerHTML property insertion
DOM Creation
This is a validatin question? Can someone validate that this is the trade-offs for determining how to update the client (i.e. javascript) when considering complexity and speed?
Research:
I'm not concerned with security like they are here->
InnerHTML vs. DOM - Security
InnerHTML vs. DOM
This is not a duplicate as it covers only part of my question.

In my experience they are basically comparable in performance. However if you use the DOM approach you get better accessibility to the power of closures so you can bind data and functions to the individual DOM elements directly.
For performance, the main thing, regardless of approach, is to hide or remove the part of the DOM you want to modified, make all you alterations outside the DOM, then put it back into the DOM as one single operation to avoid unnecessary reflows (repaints) in the browser.

From my own personal tests they're all fast enough for most needs. But if you're doing something crazy like creating thousands of elements to a page the fastest way is to use document fragments. John Resig wrote a good blog post about it. http://ejohn.org/blog/dom-documentfragments/

It is not necessarily true that DOM insertion is faster than updating innerHTML, see benchmarks at http://segdeha.com/experiments/innerhtml/ and http://www.quirksmode.org/dom/innerhtml.html, for example. Implementing the innerHTML solution might be quicker, just note that it is not available when using XHTML.

Lots of jsPerf benchmarks cover this topic; try searching the web for "jsperf innerhtml domelement" or other meaningful combinations of your search.

Related

Should I select DOM elements via id/class names or data attributes?

A co-worker suggested to change our full JavaScript code to select DOM elements only via data attribute instead of id/class names.
He says, this is bad:
$('#foo')
$('.bar')
And this is good:
$('[data-foo]')
I didn't know that there is a benefit to this so I googled up a bit and found these two blog posts:
Contra data attributes: http://intuio.at/en/blog/dont-use-data-attributes-to-find-html-elements-with-js/
Pro: http://roytomeij.com/blog/2012/dont-use-class-names-to-find-HTML-elements-with-JS.html
Since these blog articles are just opinions of two developers I'd like to know what's the actual practical experience with this? Is there a real benefit to using data-attributes for DOM selection or is it a stupid idea?
$('#foo') is fastest, but with an id only ONE element can have the Id
$('.bar') is faster than data-attributes, but are messy because class usually is associated with css styling
$('[data-foo]') is the slowest (marginally) but is the least likely to interfere with other actions
speed test - http://jsperf.com/data-selector-performance
Why You Should Use Data Attributes
If you use jQuery only, your whole logic will be bound to the DOM really closely. In big projects problems will occur. Your designer does probably think about a new naming convention and this will result in borken jQuery code. Lower performance is only a problem for a huge DOM or large amounts of selectors. Using data-attributes gives you a better seperation of styling and logic/controllers.
Why You Should NOT Use Data Attributes
jQuery itself was built for DOM manipulation mainly and therefore the tight bonding was somehow intended. Meaning the site was probably already built or designed and you want to manipulate it afterwards. If your focus is on architecture, test-driven development, maintenance and you want to achieve a better seperation of design and logic there are frameworks such as angularjs, which have indeed their own kind of data attributes (ng-directives). So there is probably a better choice if you want to think in terms of architecture.

Why cache jQuery objects?

So why are we supposed to cache jQuery objects?
In the following scenario:
var foo = $('#bar');
foo.attr('style','cool');
foo.attr('width','123');
$('#bar').attr('style','cool');
$('#bar').attr('width','123');
Why is the first option so much better than the second option?
If it's because of performance, how does it reduce usage?
Because the jQuery function has a lot of code in it, which involves unnecessary overhead if you execute it more than once with the same inputs expecting the same outputs. By caching the result, you store a reference to the exact element or set of elements you're looking for so you don't have to search the entire DOM again (even if it's a fairly fast search). In many cases (simple pages with small amounts of code) you won't notice a difference, but in the cases where you do it can become a big difference.
You can see this in action by testing your example in jsPerf.
You can also think of it as an example of the Introduce Explaining Variable refactoring pattern for readability purposes, particularly with more complex examples than the one in the question.
The jQuery selector $('#foo') searches the entire DOM for the matching element(s) and then returns the result(s).
Caching these results means that jQuery doesn't have to search the DOM every time the selector is used.
EDIT: document.getElementById() is what jQuery uses to search the DOM, but there's never enough jQuery.

Common causes of slow performing jQuery and how to optimize the code? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Javascript (jQuery) performance measurement and best practices (not load time)
Good ways to improve jQuery selector performance?
Hello,
This might be a bit of a vague or general question, but I figure it might be able to serve as a good resource for other jQuery-ers.
I'm interested in common causes of slow running jQuery and how to optimize these cases.
We have a good amount of jQuery/JavaScript performing actions on our page... and performance can really suffer with a large number off elements.
What are some obvious performance pitfalls you know of with jQuery? What are some general optimizations a jQuery-er can do to squeeze every last bit of performance out of his/her scripts?
One example: a developer may use a selector to access an element that is slower than some other way.
Thanks
Not caching queries
I see something like this way too often (exaggerated to make a point):
$("div#container ul > li a.myselector").imagine();
$("div#container ul > li a.myselector").this();
$("div#container ul > li a.myselector").code();
$("div#container ul > li a.myselector").in();
$("div#container ul > li a.myselector").a();
$("div#container ul > li a.myselector").loop();
Binding events to all rows in a table...when the table has 1000+ rows
This smells bad:
$("table tr").click(function(){}).hover(function(){},function(){});
or worse (function declarations inside a loop [yes, each() is a loop]):
$("table tr").each(function(){
$(this).click(function(){});
$(this).hover(function(){},function(){});
});
instead you can do:
$("table").delegate("click","tr",function(){}); //etc
jQuery performance usually comes down to selector performance. The following are guidelines I provide to the team Im currently working with:
Cache your selectors
Try use Id's instead of classes eg $('#myDiv')
Qualify your classes with the type of element eg $('div.content')
2019 edit:
Modern browsers expose a very efficient getElementsByClassName() method that returns the elements having a given class. As seen in this answer.
So in modern browsers, $('.content') is faster than $('div.content')
$('.content') // 925,600 ops/s ±0.9%
$('div.content') // 548,302 ops/s ±1.2% --- 40.76% slower
Provide a scope for your selector , especially if nested inside another selector eg $('div.content', this)
Use chaining of selected elements eg $('div.content').css('display', 'block').show();
There are also non-selector based optimisations such as
Upgrade to the latest version of jQuery! Each release seems to bring more performance enhancements
Make sure you are using the minified
version of jQuery.
Minify your own jQuery code (Google Closure compiler is the best imho)
Beware of poorly written third party plug-ins
Move your jQuery script tags (including jQuery) to the bottom of the page - this gives a faster page load time.
Understand the difference between statically bound events and live events (using the live or delegate functions)
When appending to the DOM, try group all the code into one insert instead of lots of little appends
Also, be sure to find out about javascript performance optimisations, as these two things go hand in hand and can make a huge difference.
In some cases, an overuse of jQuery itself can be cause for slower performance. For example, $('#selector').html(<VALUE>) has more overhead than document.getElementById('selector').innerHTML = <VALUE>;
Usually the biggest single thing you can do is improve your DOM selectors to limit the amount of querying/walk-throughs when carrying out actions. I'd suggest googling "improve jquery performance" for the tons of blog articles on the topic since the question is vague. Here are two that cover the points I mostly think about when doing my own jquery coding:
http://jonraasch.com/blog/5-performance-tuning-tricks-for-jquery
http://hungred.com/useful-information/jquery-optimization-tips-and-tricks/
The most obvious performance bottleneck is none-cached queries:
$('.selector').hide();
// and later
$('.selector').css("height", "23px");
// and even later still
$('.selector').attr("src", "http://blah.com");
This is a very primitive example but matching many elements and looping at the same time could drastically reduce performance, especially on browsers that don't support querySelectorAll or where using complex selectors that aren't supported by the browser (thus requiring use of Sizzle to do all the DOM iteration). Storing the matched collection in a variable is the smart thing to do:
var $sel = $(".selector");
$sel.hide();
// and later
$sel.css("height", "23px");
// and even later still
$sel.attr("src", "http://blah.com");
Well jQuery performance is synonymous with Javascript performance. There are lots of articles about this. Check out some tips here
There are also some good slides on this by Nicolas Zakas (Yahoo! Front End Engineer and author of Javascript Performance books) here
Here are the important tips:
Limit DOM Manipulation and DOM
Parsing - parse by ID when you can
because it is fastest. Parsing by
Class is way slower.
Limit what you do inside Loops
Check Variable Scope and Closures and
use Local Variables
Check your Data Access Methods - it
is best to access data from Object
Literals, or a local variable
The deeper the property is within an
object, the longer it takes to access

Disregarding speed and compatibility, why not use only classes and never use IDs in HTML/CSS? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
I use only classes and never use IDs.
Many people like to use IDs for different reasons.
I've seen many questions regarding IDs vs classes on stackoverflow, but no one addressed pure code organization point of view disregarding compatibility and runtime performance.
From code organization point of view, I think that using IDs is bad just like using global variables in Visual Basic code.
One reason is that IDs have to be unique which introduces unnecessary and bad dependency between different independent parts of your code (controlling different parts of HTML DOM tree).
Another reason is that making new class names is actually easier than ID names because with IDs you have to worry about global scope and with class names you need to worry only about uniqueness in local scope, same benefit as with local variables.
Most people will argue that performance of addressing by ID is better than by class and I will agree with that. But as browsers become more advanced with native implementations of CSS addressing from javascript and computers become faster, performance becomes less and less important. So let's disregard it and concentrate only on organization of code in context of current question.
This discussion started here, but my potentially wrong advice generates negative points and became too big to keep in comments, so here I try to convert it into something positive and manageable.
One visible point in favor of IDs is to use them as a tool of rule prioritization because priority of #name is higher than priority of .name.
My response: using IDs to raise priorities is bad hack, it's cleaner and there is more freedom if you use additional root elements inserted between body and other levels of tree, for example priority of body div div span.class1{} is higher than body div span.class1{} is higher than body span.class1{} is higher than span.class1{}. Another tool to use for that purpose is !important.
Some may argue that using more root elements means more difficulties when the page structure changes, but I don't think this is the case because you never have to put anything between body and designated for prioritization divs. Those divs can always stay below body and above all other content.
Another interesting association was brought about pointers and that IDs are not bad because pointers are not bad.
My response: pointers are bad if you hardcode absolute memory address in your code. Using relative pointers is always better (examples: using segments(CS,DS,SS,ES) in 8086 CPU; relative variable and method addresses generated by compilers). If we consider DOM tree as memory and compare using ID to using class then #name represents absolute memory address, but div.tab1 .name represents relative address (relative to div.tab1).
Another supporting point that I've seen for IDs is that elements with IDs are more easily available in javascript as becoming global properties. My response: again, this is like saying that global variables in Visual Basic are more conveniently available. The problem is that you can't keep large enough global (or any other) namespace in order without introducing naming hierarchy like level1_level2_name, which is just a hack to replace one namespace mechanism with another. DOM tree is convenient enough to organize namespaces, why disregard it ?
Namespace simulation inside IDs using underscore is bad because you can't establish naming context and will have to duplicate all paths everywhere in your code. That practically means that you won't be able to use CSS preprocessors that fix inability of CSS to use contexts.
quick answer: its a best practice, if you have only one instance of something and you only want one instance if it, use an ID to define that there should only be one instance of it.
This is like the difference between constant variables vs regular variables. You can use a regular variable to be a constant variable, but its better to define it as such if that is what its intended to be.
It lets fellow programmers (and yourself) know more information about the object.
I agree with you in general: Classes are much cleaner to use; you can create "namespaces" and clean cascades with them; and they can be combined: class='class1 class2'.
IDs still have their place when you're addressing really unique elements on the page, especially when addressing an element that is going to be changed in JavaScript later (e.g. a hidden overlay.)
I look at classes and ids the same way I look at a (programming) class versus an object. An object is one, specific instance of a class. I want all my classes to share a certain number of behaviors, but an individual object may have its own unique properties. CSS classes are for applying properties to broad groups of similar items, ids are for specific items and the specificity hierarchy reflects that.
To invert your question, why use classes at all when you could achieve the same effects with very specific tag selectors? For ease of use, repeatability and clarity of intent.
For me, I like using IDs on HTML elements that are absolutely unique, and classes on things that are possibly non-unique (regardless of whether or not they are).
For example, I would use <div id="header"> because there can only be one header. But I would use <div class="profile"> if there could conceivably be more than one on the page (even if there is only one). This makes the CSS a little easier for me to understand.
"DOM tree is convenient enough to organize namespaces, why disregard it ?"
Because the DOM can change due to AJAX or other javascripty-goodness.
I like #ocdcoder 's constant/variable analogy. Sometimes you want to refer to exactly that particular element. Having to adhere to a strict DOM namespace is a straightjacket that doesn't help maintenance at all, imho.
I think the discussion is incomplete without addressing the underlying reason for using classes and IDs. Saying that either should be used in every situation does not work well generally and historically.
The original purpose of classes was to attach presentation to the document, or introduce style as a separate concern than the structure of the document itself. Please correct me if I am wrong, but I think you are trying to address the problem of attaching semantic information to the elements rather than just style. If that is indeed the case, then classes serve two purposes for us - controlling presentation, and acting and semantic tags. IDs serve the purpose of acting as a unique semantic tag.
XML is highly extensible and allows namespaces which was supposed to be used in XHTML documents to assign meaning to a document as authors saw fit. But there were none in HTML and maybe it was browser incompatibilities or the non ease of use (as Tom mentioned), but most web pages and applications did not take the path of using namespaces in XHTML.
Surely the HTML spec authors saw the glaring need for attaching semantic data to HTML documents and introduced the data- attributes in HTML5 that could be assigned to any element. I would argue that if it's semantic meaning that you are concerned with, this is absolutely the best approach so far, but again browser incompatibilities have always had a major role in determining which spec becomes more commonplace and I hope IE does not have their say this time.
Using an id attribute allows you to link to an element E.g. if you’ve got this HTML:
<div id="log-in">
you can link to the log in section of the page using href="#log-in".
You’re quite right that classes are usually the most convenient and appropriate way to identify page components. But assuming that you’ve got an element that only appears once per page, and assuming you can give it an appropriate name or generate one, I don’t think you’re likely to run into problems using an id for it.

JSONML vs. InnerHTML vs.?

First of all, am I the only person using JSONML? And second of all, would you recommend using JSONML for inserting dynamic HTML or is InnerHTML more efficient?
Bare in mind that (in IE) not every innerHTML is writable (innerHTML isn't standar compilant anyway). So closer you come to appending nodes rather then inserting html, better you are. As far as I can see, jsonml thingie creates DOM elements whch is nice. I can only sugest you to make some huge dataset, insert it in two different ways and mesure performance yourself.
While superficially used to perform similar tasks, JsonML and innerHTML are quite different beasts.
innerHTML requires you to have all the markup exactly as you want it ready to go, meaning that either the server is rendering the markup, or you are performing expensive string concatenations in JavaScript.
JsonML opens the door to client-side templating through JBST which means that your template is converted from HTML markup into a JavaScript template at build time. At runtime, you simply supply the data and you end up with DOM elements to be inserted or to replace an existing element (something innerHTML cannot easily do without extra DOM creation). Rebinding only requires requesting additional data, not the entire re-rendered markup. This is where large performance gains can be made as the markup can be requested/cached separately from the data.
For simplicity, innerHTML has been the preferred method for the HTML-Message pattern style of Ajax. But tool-sets like JsonFx can make using JsonML and JBST just as easy while delivering a full browser-side templating Ajax pattern.
JsonML and the connected libraries (templating, etc.) seem to offer an efficient way of generating dynamic HTML on the client side.
When I say efficient I mean, I mean that the programmer does not waste time or effort while completing his task. But I am not sure if you meant to ask whether using innerHTML is faster and requires less resources on the client side.

Categories

Resources