jQuery DOM操作效率 - 使用JavaScript构建整个页面 [英] jQuery DOM manipulation efficiency - building entire page with JavaScript

查看:61
本文介绍了jQuery DOM操作效率 - 使用JavaScript构建整个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将开始使用一个完全空白的页面(除了html,head和body之外没有其他元素),然后使用jQuery构建页面。页面内容将采用AJAX请求中的JSON格式。 JSON中的内容不会包含任何HTML。将根据JSON对象的结构为页面的不同部分构建包含内容的HTML。

I'm going to be starting off with a completely blank page (no elements other than html, head and body) and will then build the page using jQuery. The page contents will be in the form of JSON from an AJAX request. The contents from JSON will not have any HTML. The HTML with content will be built for different sections of the page depending on the structure of the JSON object.

此页面将包含各种滑块,模态和其他动态内容。

This page will have various sliders, modals and other "dynamic" content.

我的问题是,将会它更快(让IE7作为最低标准)将HTML构建为一个大字符串(使用比标准连接快得多的字符串构建器)并以批量方式将其注入到正文中,即

My question is, will it be faster (lets take IE7 as the lowest common denominator) to build the HTML as one large string (using a string builder which is much faster than standard concatenation) and inject this into the body in a bulk fashion, i.e.

var html = "<div id='content'><p>All markup required for the page, built from the contents of the JSON object</p></div><div id='slider'>...</div>...etc."
$("body").html(html)

然后当它在DOM,使用jQuery查找并应用插件到各种动态部分,即

And then when that is in the DOM, use jQuery to find and apply plugins to the various dynamic parts, i.e.

$("#slider").sliderPlugin(options);

OR

将每个元素(或某些元素)创建为变量,然后附加到正文会更好吗? ie

Would it be better to create each element (or some) as a variable, then append to the body? i.e.

var content = $('<div/>', {id: "content"})
var slider =  $('<div/>', {id: "slider", html="<ul><li>...</li></ul>"}).appendTo(content);
$('body').append(content)

然后用这种方法我不要不必查询DOM,我只需要这样做:

then with this approach I don't have to query the DOM, I only have to do this:

slider.sliderPlugin(options);


推荐答案

我认为构建HTML一次是最好的方法,我依旧记得在某个地方读过这篇文章

I guess building the HTML once is the best way, I vaguely remember reading this somewhere

编辑:我读了它这里有更多jQuery优化。一个不错的推荐阅读

edit: I read It here with many more jQuery optimizations. a nice and recommended read

这篇关于jQuery DOM操作效率 - 使用JavaScript构建整个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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