Store HTML code in variable (faster for the browser?) - javascript

Is there a difference between ...
this
<html>
...
<div id="myDiv"> </div>';
...
</html>
var manyHtmlCode = ' ... many Html Code ... ';
// onclick -> write it in to the DIV -> $('myDiv').append(manyHtmlCode);
and this
<html>
...
<div id="myDiv" style="display:none;"> ... many Html Code ... </div>';
...
</html>
// onclick -> show content $('myDiv').show();
It is obvious to me that the second solution is faster in javascript, but what about with the browser speed?
Is the browser faster (for example, draging a div) with a smaller HTML code in the body Tag?
If so, it would be better to store not needed HTML code in a JS var. My Problem is that i have a page with many many draggable divs. Imho is the dragspeed better when the html code is smaller.

The second solution is faster for two reasons:
The HTML in this approach is 'static' HTML; it exists in the response to the browser, and doesn't need to be parsed or interpreted by JavaScript to get added to the page.
When parsing and rendering the HTML, the browser will notice the display: none and not bother rendering that element nor anything inside it. This speeds up the initial render of the page, because it doesn't actually render a lot of your HTML.

I would use second one, because it is faster to execute. (1 call of jQuery instead of 2)

If you have too many DOM items then i would suggest go with first one.
Suppose you want to traverse DOM and look for an element , if you have less elements then traversing will take less time.
My suggestion is to benchmark your code. And use the one that suits best to you.
You can use below tool
http://jsperf.com/

Depends on what exactly you wanna achieve. Yes the second one would obviously be faster as the HTML is already present in the Document, which the jQuery unhides. While in the 1st method the jquery is writing the content in real time.
Again there may be different ways to achieve what you are trying, like you could write divs u have edited into a file using ajax etc etc .. and remove it from the current document. Thus reducing the amount of html in the document.
I'm just giving you an idea here.. the thing is u haven't clearly explained what you are trying to achieve to give you the most suitable solution

Is there a difference between ...
It depends on the meaning of "is".
On a particular version of a particular browser, one or the other will run faster. You can, if you wish, benchmark them on five or 10 different browser versions and find out which usually wins.
But so what? The user won't be able to tell the difference; the user's computer typically isn't doing anything else, so there's no point in conserving the CPU cycles.
My advice to all programmers -- but especially to programmers writing for browsers -- is to ignore time and space efficiency until you see a problem and focus on
Correctness -- the code performs as designed, even in the face of unexpected inputs, changes in the underlying platform, and similar challenges;
Maintainability -- the code is written so it can be altered as requirements change; and
Usability -- the code presents an interface (either the UI in the case of end-user code or API in the case of library code) that allows a user who lacks a complete appreciation of the code to still use it correctly.
Efficiency, bah.

Related

Display DOM node in multiple places w/o cloning/copying

Disclaimer:
I've blathered on kind-of excessively here in an attempt to provide enough context to pre-empt all questions you folks might have of me. Don't be scared by the length of this question: much of what I've written is very skim-able (especially the potential solutions I've come up with).
Goal:
The effect I'm hoping to achieve is displaying the same element (and all descendants) in multiple places on the same page. My current solution (see below for more detail) involves having to clone/copy and then append in all the other places I want it to appear in the DOM. What I'm asking for here is a better (more efficient) solution. I have a few ideas for potentially more efficient solutions (see below). Please judge/criticize/dismiss/augment those, or add your own more-brilliant-er solution!
"Why?" you ask?
Well, the element (and it's descendants) that I'm wanting to display more than once potentially has lots of attributes and contents - so cloning it, and appending it someplace else (sometimes more than one other place) can get to be quite a resource-hogging DOM manipulation operation.
Some context:
I can't describe the situation exactly (damn NDA's!) but essentially what I've got is a WYSIWYG html document editor. When a person is editing the DOM, I'm actually saving the "original" node and the "changed" node by wrapping them both in a div, hiding the "original" and letting the user modify the new ("changed") node to their heart's content. This way, the user can easily review the changes they've made before saving them.
Before, I'd just been letting the user navigate through the "diff divs" and temporarily unhiding the "original" node, to show the changes "inline". What I'm trying to do now is let the user see the whole "original" document, and their edited ("changed") document in a side-by-side view. And, potentially, I'd like to save the changes through multiple edit sessions, and show 'N' number of versions side-by-side simultaneously.
Current Solution:
My current solution to achieve this effect is the following:
Wrap the whole dang dom (well, except the "toolbars" and stuff that they aren't actually editing) in a div (that I'll call "pane1"), and create a new div (that I'll call "pane2"). Then deep-clone pane1's contents into pane2, and in pane1 only show the "original" nodes, and in pane2 only show the "changed" nodes (in the diff regions - everything outside of that would be displayed/hidden by a toggle switch in a toolbar). Then, repeat this for panes 3-through-N.
Problem with Current Solution:
If the document the user is editing gets super long, or contains pictures/videos (with different src attributes) or contains lots of fancy styling things (columns, tables and the like) then the DOM can potentially get very large/complex, and trying to clone and manipulate it can make the browser slow to a crawl or die (depending on the DOM's size/complexity and how many clones need to be made as well as the efficiency of the browser/the machine it's running on). If size is the issue I can certainly do things like actually remove the hidden nodes from the DOM, but that's yet more DOM manipulation operations hogging resources.
Potential Solutions:
1. Find a way to make the DOM more simple/lightweight
so that the cloning/manipulating that I'm currently doing is more efficient. (of course, I'm trying to do this as much as I can anyway, but perhaps it's all I can really do).
2. Create static representations of the versions with Canvas elements or something.
I've heard there's a trick where you can wrap HTML in an SVG element, then use that as an image source and draw it onto a canvas. I'd think that those static canvasses (canvi?) would have a much smaller memory footprint than cloned DOM nodes. And manipulating the DOM (hiding/showing the appropriate nodes), then drawing an image (rinse & repeat) should be quicker & more efficient than cloning a node and manipulating the clones. (maybe I'm wrong about that? Please tell me!)
I've tried this in a limited capacity, but wrapping my HTML in SVG messes with the way it's rendered in a couple of weird cases - perhaps I just need to message the elements a bit to get them to display properly.
3. Find some magic element
that just refers to another node and looks/acts like it without being a real clone (and therefore being somehow magically much more lightweight). Even if this meant that I couldn't manipulate this magic element separately from the node it's "referencing" (or its fake children) - in that case I could still use this for the unchanged parts, and hopefully shave off some memory usage/DOM Manipulation operations.
4. Perform some of the steps on the server side.
I do have the ability to execute server side code, so maybe it's a lot more efficient (some of my users might be on mobile or old devices) to get all ajax-y and send the relevant part of the DOM (could be the "root" of the document the user is editing, or just particularly heavy "diff divs") to the server to be cloned/manipulated, then request the server-manipulated "clones" and stick 'em in their appropriate panes/places.
5. Fake it to make it "feel" more efficient
Rather than doing these operations all in one go and making the browser wait till the operations are done to re-draw the UI, I could do the operations in "chunks" and let the browser re-render and catch a breather before doing the next chunk. This probably actually would result in more time spent, but to the casual user it might "feel" quicker (haha, silly fools...). In the end, I suppose, it is user experience that is what's most important.
Footnote:
Again, I'm NDA'd which prevents me from posting the actual code here, as much as I'd like to. I think I've thoroughly explained the situation (perhaps too thoroughly - if such a thing exists) so it shouldn't be necessary for you to see code to give me a general answer. If need be, I suppose I could write up some example code that differs enough from my company's IP and post it here. Let me know if you'd like me to do that, and I'll be happy to oblige (well, not really, but I'll do it anyway).
Take a look at CSS background elements. They allow you to display DOM nodes elsewhere/repeatedly. They are of course they are read-only, but should update live.
You may still have to come up with a lot of magic around them, but it is a similar solution to:
Create static representations of the versions with Canvas elements or something.
CSS background elements are also very experimental, so you may not get very far with them if you have to support a range of browsers.
To be honest, after reading the question I almost left thinking it belongs in the "too-hard-basket", but after some thought perhaps I have some ideas.
This is a really difficult problem and the more I think about it the more I realise that there is no real way to escape needing to clone. You're right in that you can create an SVG or Canvas but it won't look the same, though with a fair amount of effort I'm sure you can get quite close but not sure how efficient it will be. You could render the HTML server-side, take a snapshot and send the image to the client but that's definitely not scalable.
The only suggestions I can think of are as follows, sorry if they are long-winded:
How are you doing this clone? If you're going through each element and as you go through each you are creating a clone and copying the attributes one by one then this is heaavvvyy. I would strongly suggest using jQuery clone as my guess is that it's more efficient than your solution. Also, when you are making structural changes it might be useful to take advantage of jQuery's detach/remove (native JS: removeChild()) methods as this will take the element out of the DOM so you can alter it before reinserting.
I'm not sure how you'v got your WYSIWYG, but avoid using inputs as they are heavy. If you must then I'm assuming they don't look like inputs so just swap them out with another element and style (CSS) to match. Make sure you do these swaps before you reinsert the clone in to the DOM.
Don't literally put video at the time of showing the user comparisions. The last thing we want to do is inject 3rd party objects in to the page. Use an image, you only have to do it while comparing. Once again, do the swap before inserting the clone in to the DOM.
I'm assuming the cloned elements won't have javascript attached to them (if there is then remove it, less moving parts is more efficiency). However, the "changed" elements will probably have some JS events attached so perhaps remove them for the period of comparision.
Use Chrome/FF repaint/reflow tools to see how your page is working when you restructure the DOM. This is important because you could be doing some "awesome" animations that are costing you intense resources. See http://paulirish.com/2011/viewing-chromes-paint-cycle/
Use CSS over inline styling where possible as modern browsers are optimised to handle CSS documents
Can you make it so your users use a fast modern browser like Chrome? If it's internal then might be worth it.
Can you do these things in Silverlight or Adobe Air? These objects get special resource privileges, so this will most likely solve your problem (according to what I'm imagining the depth of the problem is)
This one is a bit left-field but could you open in another window? Modern browsers like Chrome will run the other window in its own process which may help.
No doubt you've probably looked in to these things more than I but good luck with it. Would be curious how you solved it.
You may also try: http://html2canvas.hertzen.com/
If it works for you canvas has way better support.
In order to get your "side-by-side" original doc and modified doc.. rather than cloning all pane1 into pane2.. could you just load the original document in an iframe next to the content you are editing? A lot less bulky?
You could tweak how the document is displayed when it's in an iframe (e.g. hide stuff outside editable content).
And maybe when you 'save' a change, write changes to the file (or a temp) and open it up in a new iframe? That might accomplish your "multiple edit sessions"... having multiple iframes displaying the document in various states.
Just thinking out loud...
(Sorry in advance if I'm missing/misunderstanding any of your goals/requirements)
I don't know if it's already the case for you but you should consider using jQuery library as it allows to perform different kinds of DOM elements manipulation such as create content and insert it into several elements at once or select an element on the page and insert it into another.
Have a look on .appendTo(), .html(), .text(), .addClass(), .css(), .attr(), .clone()
http://api.jquery.com/category/manipulation/
Sorry if I'm just pointing out something you already know or even work with but your NDA is in the way of a more accurate answer.

unobtrusive Javascript, should I use it? what is the best way to manage and organize events? how do I prevent inefficiencies?

I have been struggling with choosing unobtrusive javascript over defining it within the html syntax. I want to convince my self to go the unobtrusive route, but I am having trouble getting past the issues listed below. Can you please help convince me :)
1) When you bind events unobtrusively, there is extra overhead on the client's machine to find that html element, where as when you do stuff, you don't have to iterate the DOM.
2) There is a lag between when events are bound using document.ready() (jquery) and when the page loads. This is more apparent on very large sites.
3) If you bind events (onclick etc) unobtrusively, there is no way of looking at the html code and knowing that there is an event bound to a particular class or id. This can become problematic when updating the markup and not realizing that you may be effecting javascript code. Is there a naming convention when defining css elements which are used to bind javascript events (i have seen ppl use js_className)
4) For a site, there are different pieces of javascript for different pages. For example Header.html contains a nav which triggers javascript events on all pages, where as homepage.html and searchPage.html contains elements that trigger javascript on their respective pages
sudo code example:
header.html
<script src="../myJS.js"></script>
<div>Header</div>
<ul>
<li>nav1</li><li>nav2</li>
</ul>
homepage.html
<#include header.html>
<div class="homepageDiv">some stuff</div>
searchpage.html
<#include header.html>
<div class="searchpageDiv">some other stuff</div>
myJS.js
$(document).ready(function(){
$("ul.li").bind("click",doSomething());
$(".homePageDiv").bind("click",doSomethingElse());
$(".searchPageDiv").bind("click",doSomethingSearchy());
});
In this case when you are on the searchPage it will still try to look for the "homepageDiv" which does not exist and fail. This will not effect the functionality but thats an additional unnecessary traversal. I could break this up into seperate javascript files, but then the browser has to download multiple files, and I can't just serve one file and have it cached for all pages.
What is the best way to use unobtrusive javascript so that I could easily maintain a ( pretty script heavy) website, so another developer is aware of scripts being bound to html elements when they are modifying my code. And serve the code so that the client's browser is not looking for elements which do not exist on a particular page (but may exist on others).
Thanks!
You are confused. Unobtrusive JavaScript is not just about defining event handlers in a program. It's a set of rules for writing JavaScript such that the script doesn't affect the functionality of other JavaScript on the same page. JavaScript is a dynamic language. Anyone can make changes to anything. Thus if two separate scripts on the same page both define a global variable add as follows, the last one to define it will win and affect the functionality of the first script.
// script 1
var add = function (a, b) {
return a + b;
};
// script 2
add = 5;
//script 1 again
add(2, 3); // error - add is a number, not a function
Now, to answer your question directly:
The extra overhead to find an element in JavaScript and attach an event listener to it is not a lot. You can use the new DOM method document.querySelector to find an element quickly and attach an event listener to it (it takes less than 1 ms to find the element).
If you want to attach your event listeners quickly, don't do it when your document content loads. Attach your event listeners at the end of the body section or directly after the part of your HTML code to which you wish to attach the event listener.
I don't see how altering the markup could affect the JavaScript in any manner. If you try to attach an event listener to an element that doesn't exist in JavaScript, it will silently fail or throw an exception. Either way, it really won't affect the functionality of the rest of the page. In addition, a HTML designer really doesn't need to know about the events attached any element. HTML is only supposed to be used for semantic markup; CSS is used for styling; and JavaScript is used for behavior. Don't mix up the three.
God has given us free will. Use it. JavaScript supports conditional execution. There are if statements. See if homePageDiv exists and only then attach an event listener to it.
Try:
$(document).ready(function () {
$("ul.li").bind("click",doSomething());
if (document.querySelector(".homePageDiv")) {
$(".homePageDiv").bind("click",doSomethingElse());
} else {
$(".searchPageDiv").bind("click",doSomethingSearchy());
}
});
Your question had very little to do with unobtrusive JavaScript. It showed a lack of research and understanding. Thus, I'm down voting it. Sorry.
Just because jQuery.ready() executes does not mean that the page is visible to the end user. This is a behaviour defined by browsers and these days there are really 2 events to take into consideration here as mootools puts it DomReady vs Load. When jQuery executes the ready method it's talking about the dom loading loaded however this doesn't mean the page is ready to be viewed by the user, external elements which as pictures and even style sheets etc may still be loading.
Any binding you do, even extremely inefficient ones will bind a lot faster than all the external resources being loaded by the browser so IMHO user should experience no difference between the page being displayed and functionality being made available.
As for finding binding on elements in your DOM. You are really just fearing that things will get lost. This has not really been my actual experience, more often than not in your JS you can check what page you are on and only add javascript for that page (as Aadit mentioned above). After that a quick find operation in your editor should help you find anything if stuff gets lost.
Keep in mind that under true MVC the functionality has to be separate from the presentation layer. This is exactly what OO javascript or unobtrusive javascript is about. You should be able to change your DOM without breaking the functionality of the page. Yes, if you change the css class and or element id on which you bind your JS will break, however the user will have no idea of this and the page will at least appear to work. However if this is a big concern you can use OO-Javascript and put div's or span's as placeholders in your dom and use these as markers to insert functionality or tell you that it exists, you can even use html comments. However, in my experience you know the behavior of your site and hence will always know that there is some JS there.
While I understand most of your concerns about useless traversals, I do think you are nickle and dime'ing it at this point if you are worried about 1 additional traversal. Previous to IE8 it used to be the case that traversing with the tag name and id was a lot faster than my selector but this is no longer true infact browsers have evolved to be much faster when using just the selectors:
$("a#myLink") - slowest.
$("a.myLink") - faster.
$("#Link") - fastest.
$(".myLink") - fastest.
In the link below you can see that as many as 34 thousand operations per second are being performed so I doubt speed is an issue.
You can use firebug to test the speed of each in the case of a very large dom.
In Summary:
a) Don't worry about losing js code there is always ctrl+f
b) There is no lag because dom ready does not mean the page is visible to start with.
Update
Fixed order of speed in operations based on the tests results from here
However keep in mind that performances of IE < 8 are really had if you don't specify the container (this used to be the rule, now it seems to be the exception to the rule).

How many element id's can browsers safely handle before performance degredation?

Using element id's is the fastest way for javascript to 'get' an element. Is there a rule of thumb or best practices guideline on how many of these id's should be used before one can expect browser performance to start degrading?
An ID, in and of itself, is just an attribute value. The only 'performance' issue is extra bits and bytes the browser has to download. From a JavaScript POV, the more elements in the DOM, the longer it can take to traverse it, but that's not directly related to the number of IDs you may be using.
EDIT:
To clarify if your JS is this:
document.getElementById("myID")
it doesn't matter if your HTML looks like this:
<div id="div1">
<div id="div2">
...
<div id="div999">
<div id="myDiv">
or this:
<div>
<div>
...
<div>
<div id="myDiv">
The JS should run the same for both of those examples.
A complex page means more bytes to download and it also means slower DOM access in JavaScript. It makes a difference if you loop through 500 or 5000 DOM elements on the page when you want to add an event handler for example.
A high number of DOM elements can be a symptom that there's something that should be improved with the markup of the page without necessarily removing content. Are you using nested tables for layout purposes? Are you throwing in more s only to fix layout issues? Maybe there's a better and more semantically correct way to do your markup.
A great help with layouts are the YUI CSS utilities: grids.css can help you with the overall layout, fonts.css and reset.css can help you strip away the browser's defaults formatting. This is a chance to start fresh and think about your markup, for example use s only when it makes sense semantically, and not because it renders a new line.
The number of DOM elements is easy to test, just type in Firebug's console:
document.getElementsByTagName('*').length
We've got a form with over 1,000 fields (don't ask), using jQuery Validate for client-side validation. This includes validating which fields are required, checking the data type of each field, showing/hiding groups of fields based on certain criteria and running calculations across multiple fields as data is entered.
Only MSIE slows down at this scale. Firefox and Chrome run the validation "instantly". MSIE eventually shows the "long running script" dialog. I was notified last night that additional fields are now required.

Generating/selecting non-standard HTML tags with jQuery, a good idea?

I've noticed that jQuery can create, and access non-existent/non-standard HTML tags. For example,
$('body').append('<fake></fake>').html('blah');
var foo = $('fake').html(); // foo === 'blah'
Will this break in some kind of validation? Is it a bad idea, or are there times this is useful? The main question is, although it can be done, should it be done?
Thanks in advance!
You can use non-standard HTML tags and most of the browsers should work fine, that's why you can use HTML5 tags in browsers that don't recognize them and all you need to do is tell them how to style them (particularly which tags are display: block). But I wouldn't recommend doing it for two reasons: first it breaks validation, and second you may use some tag that will later get added to HTML and suddenly your page stops working in newer browsers.
The biggest issue I see with this is that if you create a tag that's useful to you, who's to say it won't someday become standard? If that happens it may end up playing a role or get styles that you don't anticipate, breaking your code.
The rules of HTML do say that if manipulated through script the result should be valid both before and after the manipulation.
Validation is a means to an end, so if it works for you in some way, then I wouldn't worry too much about it. That said, I wouldn't do it to "sneak" past validation while using something like facebook's <fb:fan /> element - I'd just suck it up and admit the code wasn't valid.
HTML as such allows you to use any markup you like. Browsers may react differently to unknown tags (and don't they to known ones, too?), but the general bottom line is that they ignore unknown tags and try to render their contents instead.
So technically, nothing is stopping you from using <fake> elements (compare what IE7 would do with an HTML5 page and the new tags defined there). HTML standardization has always been an after-the-fact process. Browser vendors invented tags and at some point the line was drawn and it was called HTMLx.
The real question is, if you positively must do it. And if you care whether the W3C validator likes your document or not. Or if you care whether your fellow programmers like your document or not.
If you can do the same and stay within the standard, it's not worth the hassle.
There's really no reason to do something like this. The better way is to use classes like
<p class = "my_class">
And then do something like
$('p.my_class').html('bah');
Edit:
The main reason that it's bad to use fake tags is because it makes your HTML invalid and could screw up the rendering of your page on certain browsers since they don't know how to treat the tag you've created (though most would treat it as some kind of DIV).
That's the main reason this isn't good, it just breaks standards and leads to confusing code that is difficult to maintain because you have to explain what your custom tags are for.
If you were really determined to use custom tags, you could make your web page a valid XML file and then use XSLT to transform the XML into valid HTML. But in this case, I'd just stick with classes.

Tips on optimizing javascript

The things I'm trying to get my website to do are getting fairly complex, some of the things that need to be done take long enough that it gives visible delays.
Mainly, adding content to the document slows things down as well as jquery animations that I'm using.
I create elements using document.createElement("div") rather than just doing document.write("<div id='someId'></div>"), and the animations are the custom animation using .animation();
I'm wondering how I can continue to add content as I am but prevent the browser from freezing every time I want to add something.
Any suggestions for speeding things up so there is less of a delay?
Tips on what to avoid in javascript programming that gives increased delay would be really helpful.
This sounds more like you want to improve the DOM interaction performance rather than javascript, so in that vein:
Yes, document.write is bad, it blocks additional loading (any JS executing before your pages has finished loading basically requires all other processing to stop -- modern browsers like Safari (and by proxy Chrome) and Firefox do a degree of content preloading in order to prevents loads from blocking but subsequent style resolution, etc is largely blocked.
document.createElement is in general the best solution, although their are certain cases where just manipulating innerHTML on an element may be faster -- but that is not yet cross browser compatible (i think innerHTML doesn't exist till Firefox 3.5) and the perform characteristics are tricky.
Reduce the amount of content you load initially -- eg. if you have lots of content (or content that requires large scripts) attempt to delay loading until after the initial page load has completed.
Oh, for animations you should look at CSS animations and they perform much better than any JS implementations, but they're only present in Safari (and by proxy Chrome) and Firefox 3.5 -- definitely not in IE :-(
In terms of JavaScript performance, avoid with and getters/setters like the plague and you should be fine in most modern JS implementations.
I know this is a couple of years late but better late than never considering this question popped up at the top of google's list for javascript animation optimization.
If you need to add a large amount of elements to the DOM and don't want to use innerHTML to do so you can speed that up I believe by adding the elements to a documentFragment first and then injecting the documentFragment all at once into the DOM. I remember reading that DOM injection is the slowest part of using the standard API to create and add elements. documentFragment allows you to inject all of its contents into the DOM in one go eliminating a large amount of overhead caused by calling appendChild or other insertion methods multiple times. appendChild and other insertion methods supposedly don't suffer the same costs when inserting into a documentFragment opposed to inserting into the DOM. I wish I could find the article I read this in as it had some really nice benchmark tests and explanations. I'm sure you can find more information by doing some searches.
As always though which method to use should be determined by testing on a case by case basis. Eventually you'd probably learn which one to use based on structure of the elements, amount, and use.
PS. There may be an issue with styles and documentFragment but I can't remember what was said about them, either way it'd be something worth checking out.
JQuery is great for manipulating the DOM. I'd take a look at their code in order to get some ideas. Or, seeing how I'm way lazy, I'd just use their stuff.
In one of the podcasts Jeff Atwood mentioned you'd have to be crazy to write your own javascript... after using JQuery, I'd have to agree with him.
Although I am a huge fan of jQuery, and it makes development much easier, note that a jQuery statement (or in any JavaScript library) will never be as fast as its semantic equivalent in plain JavaScript because of the extra overhead.
That being said, these are my goto references whenever I want to speed up my JavaScript.
http://home.earthlink.net/~kendrasg/info/js_opt/
http://www.miislita.com/searchito/javascript-optimization.html
There is document fragment function which can make life much more easier. Here is the example use.
function appendDivs(element){
var fragment = document.createDocumentFragment();
for(var i=0;i<10;i++){
var div = document.createElement("div");
fragment.appendChild(div);
}
element.appendChild(fragment);
}
For a complete reference, you can see this post on my blog.
What surprises most people is that using innerHTML is, actually, the fastest way there is to manipulate the DOM.
You can see one benchmark here for example.
// Some functions for easier coding in DOM
function createEl(el){
return document.createElement(el);
}
function addElBody(el){
return document.body.appendChild(el);
}
function addElChild(el, child){ //el- parent
return el.appendChild(child);
}
// Example :
var container=createEl('div');
container.setAttribute('id', 'container');
addElBody(container);
var item=createEl('ul');
item.setAttribute('id', 'list');
addElBody(item);
addElChild(container, item);

Categories