Javascript jQuery最好的方式来插入一大块代码到DOM [英] Javascript jQuery best way to insert a big piece of code into DOM

查看:95
本文介绍了Javascript jQuery最好的方式来插入一大块代码到DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大块代码需要插入到DOM中。该代码还包含一些变量:

 < ul id =info'+ value +'class =info> < li class =hide>< / li>< li class =lock>< ul> 
//只是一段带有变量$的代码

现在我做:

  var codeToInsert =< some code /> 
codeToInsert.insertAfter('#someID');

从性能的角度来看,是否有更好的方法?

解决方案

如果要插入大块代码,请使用jQuery作为选择器,然后使用 innerHTML DOM属性 - 它是插入大块HTML的最快方法。
不要将要插入的字符串包装到JQuery中,将其作为字符串。



例如: $('# somePlaceholder')[0] .innerHTML = myHTMLString;



http://www.quirksmode.org/dom/w3c_html.html


一般来说,innerHTML比普通的DOM方法要快,因为HTML解析器总是比DOM引擎快。如果要进行复杂的更改,请使用innerHTML。 (对于简单的更改,使用哪种方法并不重要,尽管innerHTML在理论上更快)。


如果您在字符串连接JS创建一个数组, push()部分和 join()在结尾,而不是用例如 + = + 。它有所不同esp在IE中。


I have a big piece of code that needs to be inserted into DOM at some point. The code also contain some variables:

<ul id="info'+value+'" class="info"><li class="hide"></li><li class="lock"><ul>
// just a piece of the code with variable "value"

Right now I am doing:

var codeToInsert = "<some code/>"
codeToInsert.insertAfter('#someID');

Is there a better way to do it from the performance point of view?

解决方案

If you want to insert big piece of code, use jQuery for its selector and then use the innerHTML DOM property - it is the fastest way to insert a big chunk of HTML. Do not wrap the string that is to be inserted into JQuery, leave it as a string.

E.g.: $('#somePlaceholder')[0].innerHTML = myHTMLString;.

http://www.quirksmode.org/dom/w3c_html.html:

In general innerHTML is faster than normal DOM methods because the HTML parser is always faster than the DOM engine. If you want to do complicated changes, use innerHTML. (For simple changes it does not really matter which method you use, although innerHTML remains theoretically faster.)

If you do string concatenation in JS, create an array, push() the parts and join() at the end instead of appending with e.g. += or +. It makes a difference esp. in IE.

这篇关于Javascript jQuery最好的方式来插入一大块代码到DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆