Vani
Vani

Reputation: 71

html template vs pushing code through js

Say I want to render some html dynamically. Which is better?(apart from it gives good structure to code)

<script type="text/template" id="some">
//some html code here
</script>
_.template($("#someid").html());

or

$("#someid").html("inserting html here");

Upvotes: 2

Views: 239

Answers (2)

Adassko
Adassko

Reputation: 5343

I would use an invisible div rather than html code in script tag so google could index it.

Also I would use .clone() method to clone DOM structure instead of retrieving plain text html (.html()) and creating new element based on this. But it would be a bit more tricky to change values in the template - still it might be quicker; haven't tested.

Upvotes: 0

Vikram Deshmukh
Vikram Deshmukh

Reputation: 15646

In both the approaches that you've mentioned, the HTML markup is generated as HTML string and then added to the target DOM element. So, the way I see it there is no performance benefit of using one over the other.

  • Having said that, using templates (underscore) in your case, the code just becomes more manageable than having to generate long HTML strings by concatenating various values together.

  • Also, compiled templates with conditional statements can be stored in a variable and reused by making a single call to the template (and passing an object to it). Whereas, if you need to populate HTML string then in that case you'll end up writing a string concatenation statement inside a for loop or its functional programming equivalent $.each or _.each to make it reusable.

Here are 2 fiddles that essentially do the same thing using the 2 said approaches:

Using Templates

Using string concatenation

Compare the code and decide for yourself what best suits your requirement.

Upvotes: 1

Related Questions