将一大段代码插入 DOM 的 Javascript jQuery 最佳方法 [英] Javascript jQuery best way to insert a big piece of code into DOM

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

问题描述

我有一大段代码需要在某个时候插入到 DOM 中.该代码还包含一些变量:

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"

现在我在做:

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

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

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

推荐答案

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

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.

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

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

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

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.)

如果您在 JS 中进行字符串连接,请创建一个数组,push() 部分和最后的 join() 而不是附加例如+=+.它有所作为,尤其是.在 IE 中.

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.

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

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