[英]html template vs pushing code through js
Say I want to render some html dynamically. 说我想动态呈现一些html。 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");
In both the approaches that you've mentioned, the HTML markup is generated as HTML string and then added to the target DOM element. 在您提到的两种方法中,HTML标记都是作为HTML字符串生成的,然后添加到目标DOM元素中。 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. 话虽这么说,在您的情况下使用模板(下划线),代码变得比必须通过将各种值连接在一起来生成长HTML字符串更易于管理。
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. 而如果您需要填充HTML字符串,那么在这种情况下,您最终将在for
循环或其等效功能的$.each
或_.each
编写一个字符串连接语句,以使其可重用。
Here are 2 fiddles that essentially do the same thing using the 2 said approaches: 这里有2个小提琴实质上使用上述2种方法来做同样的事情:
Using string concatenation 使用字符串串联
Compare the code and decide for yourself what best suits your requirement. 比较代码并自己决定最适合您的要求。
I would use an invisible div
rather than html code in script
tag so google could index it. 我会在script
标签中使用不可见的div
而不是html代码,以便Google对其进行索引。
Also I would use .clone()
method to clone DOM structure instead of retrieving plain text html ( .html()
) and creating new element based on this. 另外,我将使用.clone()
方法克隆DOM结构,而不是检索纯文本html( .html()
)并基于此创建新元素。 But it would be a bit more tricky to change values in the template - still it might be quicker; 但是更改模板中的值会比较棘手-仍然可能更快。 haven't tested. 还没测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.