Issues with jQuery Methods Like .append and How to Fix Them

efficiencyjavascriptjquery

tl;dr: What is wrong with the efficiency of methods such as .append() and what can be alternatives to this?

Explanation:
Hello everyone. I occasionally have to build A/B tests for websites, which means that i have to change sites using only jQuery(or javascript of course) to alter appearances and functionalities of websites. This means no 'hard'-html/css or the likes. Now i'm pretty much the only one with the slightest knowledge of javascript that works here, so i don't get much peer reviews. Now we are working with a customer and their developer sends me this feedback:

'jQuery isn't used optimally by appending seperate/loose items into the DOM'.

An example of this is an accordeon item i added to the site, by typing (something along the lines of):

$('#site_container').append('<div id="container"><div id="container_click">Content to click on</div></div id="container_expand">Content to be shown when expanded</div></div>');
$('#container_click').click(function(){//animate to height function here});

Now i've already tried to do my own research, and i know typing an entire element with it's content in 1 string is not as secure as making an object and then adding attributes to that object. For a temporary test however, i do not think this is such a big issue, since they only tend to live for a week or 2.

I do realise the solution feels a bit flimsy, but i do not really see a different approach.

Now my question is: What does the other developer mean with optimally? Is there a big part of jQuery i'm missing? Is there a way to approach problems like these more efficiently?

Best Answer

What they probably meant is that manipulating the DOM is slow and that you can avoid injecting HTML through jQuery.

What you can do, instead, is to have A/B variants both in your original HTML. Then, you hide the B variant by default, and switch from A to B by simply hiding the one and showing the other.

An even better alternative is to have two HTML templates, one for A variant, another one for B. This way, you don't even need to rely on JavaScript.


Performance-wise, I'm not sure if you need to take in consideration their remark. Unless you're doing a lot of DOM manipulation, you .append() maybe slows down the page by a few milliseconds or even microseconds. Unless you've profiled the app and determined that your .append() is the actual bottleneck, don't bother.

You may, on the other hand, be interested by 43,439 reasons to use append() correctly blog article and by .append VS .html VS .innerHTML performance answer on Stack Overflow.

Related Topic