问题描述
我有它的一些信息的JavaScript对象。
我有2个选择,我能想到的创建从该对象中的HTML。我想知道哪一个是做事情的正确方法这只是所有preference?
1)通过这个数组的JavaScript循环,创造与jQuery的HTML?
2)阿贾克斯后/熬过这个对象(PHP数组对象为PHP和循环),并创建HMTL呀?然后返回一个JSON恩codeD在它的HMTL对象回来了,它附加到一个div?
我目前还建立
VAR OutterDiv = $(document.createElement方法('格'));
循环{
OutterDiv.append(<跨度>一些信息< / SPAN>中);
VAR InnerDiv = $(document.createElement方法('格'));
循环{
InnerDiv.append(<跨度>一些信息< / SPAN>中);
InnerDiv.append(<跨度>一些信息< / SPAN>中);
}
OutterDiv.append(InnerDiv);
}
$(#内容)追加(OutterDiv)。
你为什么不遍历对象,并创建JavaScript的HTML字符串?然后插入该字符串,无论你需要它吗?我相信这是可以做到你想要什么做的最快方法。其主要思想是,连接字符串是不是插入的DOM元素速度更快,而且可能比所造成的HTTP请求的等待时间更快。
** 修改 **
Apparantly,IE是字符串连接(大惊喜),并使用<较慢href="http://stackoverflow.com/questions/3667469/javascript-jquery-best-way-to-insert-a-big-piece-of-$c$c-into-dom">array为更好的。例如:
VAR HTML = [];
对于 (...) {
html.push(小于从这里你对象&gt一些HTML内容);
}
$(选择)。html的(html.join(''));
//找到你需要处理的元素,并在这里进行绑定
//例如:$('#someelment)单击(...);
这可能是一样快,你可以得到的。
** 更新 **
在执行了JavaScript构建HTML的任务仍然普遍较快,经过一些测试,似乎连接字符串,或建筑物数组不是比创建文本节点更快。该测试可以查看和分叉的 jsfiddle.net 或在这里它是用于归档pruposes:
函数的runTest(testFn,持续时间){
VAR endTime的= +新的日期()+持续时间;
变种运行= 0;
变种charCount = 0;
而(+新的Date()&LT; endTime的){
charCount + = testFn();
++运行;
}
拆除();
//console.log(testFn.title,'跑',运行,时代。');
$('#日志)追加($('&LT; DIV&GT;&LT; / DIV&GT;)文本(testFn.title +'跑'+跑+'倍('+(charCount / 1000)+'CPS )'))。
}
///
功能拆解(){
而(targetDiv.firstChild){
targetDiv.removeChild(targetDiv.firstChild);
}
}
///
VAR TESTDATA;
变种样本,的sampleData;
传播generateTestData(){
TESTDATA = {};
为(变种I = 0; I&≤(的Math.random()*(样品[1] -sample [0]))+试样[0];我++){
TESTDATA ['条目'+ I] = randomString();
}
}
功能randomString()
{
VAR文本=;
VAR可能=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789;
为(变种I = 0; I&≤(的Math.random()*(的sampleData [1] -sampleData [0]))+的sampleData [0];我+ +)
文字+ = possible.charAt(Math.floor(的Math.random()* possible.length));
返回文本;
}
功能洗牌(ARR){
VAR的len = arr.length;
VAR I = len个;
当我 - ) {
VAR P = parseInt函数(的Math.random()* LEN);
VAR T =改编[I]
改编[i] = ARR [P]。
ARR [P] = T;
}
返回ARR;
};
///
变量$ targetDiv = $('#targetDiv');
变种targetDiv =的document.getElementById('targetDiv');
///
功能JQ(){
变种的HTML = [];
变种数= 0;
为(在TESTDATA VAR键){
数+ = TESTDATA [关键] .length;
html.push('&LT; DIV&GT;'+ TESTDATA [键] +'&LT; / DIV&GT;');
}
$ targetDiv.html(html.join(''));
返回计数;
}
函数内部(){
变种的HTML = [];
变种数= 0;
为(在TESTDATA VAR键){
数+ = TESTDATA [关键] .length;
html.push('&LT; DIV&GT;'+ TESTDATA [键] +'&LT; / DIV&GT;');
}
targetDiv.innerHTML = html.join('');
返回计数;
}
功能DOM(){
VAR根= document.createElement方法('格');
VAR节点;
变种数= 0;
为(在TESTDATA VAR键){
数+ = TESTDATA [关键] .length;
节点= document.createElement方法('格');
node.appendChild(document.createTextNode(TESTDATA [关键]));
root.appendChild(节点);
}
targetDiv.appendChild(根);
返回计数;
}
///
jq.title ='jQuery的html的;
inner.title ='的innerHTML';
dom.title ='DOM';
///
样本= [10,100];
的sampleData = [100,1000]。
generateTestData();
VAR时间= 1000;
VAR testFn =洗牌([JQ,内,DOM]);
$每个(testFn,函数(K,FN){
的setTimeout(函数(){的runTest(FN,持续时间);},0);
});
总体上,而每一种方法是在某些条件下更有效(大量的的或的一些数据,长的或的短字符串等),则DOM方法普遍较快似乎在所有情况下
所以,你有它。由于 GGG ,在最初的测试情况。
I have a JavaScript Object with some information in it.
I have 2 options I can think of to create the HTML from this object. I was wondering which one is the correct way of doing things of is this just all preference?
1) Loop through this array with JavaScript and create the HTML with Jquery?
2) Ajax post/get the object to PHP and loop through this object(php array) and create the HMTL that way? Then return a json encoded object back with the HMTL in it and append it to a div?
What I currently Do to build
var OutterDiv = $(document.createElement('div'));
for loop{
OutterDiv.append("<span>SOME INFO</span>");
var InnerDiv = $(document.createElement('div'));
for loop{
InnerDiv.append("<span>SOME INFO</span>");
InnerDiv.append("<span>SOME INFO</span>");
}
OutterDiv.append(InnerDiv);
}
$("#content").append(OutterDiv);
Why don't you loop through the object and create an HTML string from JavaScript? Then insert that string wherever you need it? I believe this is the fastest way you can accomplish what you want do do. The main idea is that concatenating strings is faster than inserting DOM elements, and perhaps faster than the latency caused by an Http request.
** Edit **
Apparantly, IE is slower at string concatenation (big surprise) and using an array is better.Example :
var html = [];
for (...) {
html.push( <some html content from your object here> );
}
$(selector).html(html.join(''));
// find the elements you need to handle and perform bindings here
// ex: $('#someelment').click(...);
This is probably as fast as you can get.
** Update **
While performing the task of building HTML with JavaScript is still generally faster, after some testing, it seems that concatenating strings, or building arrays are not faster than creating text nodes. The test can be viewed and forked on jsfiddle.net or here it is for archiving pruposes :
function runTest(testFn, duration) {
var endTime = +new Date() + duration;
var runs = 0;
var charCount = 0;
while (+new Date() < endTime) {
charCount += testFn();
++runs;
}
teardown();
//console.log(testFn.title, 'ran', runs, 'times.');
$('#log').append($('<div></div>').text(testFn.title + ' ran ' + runs + ' times (' + (charCount/1000) + ' cps).'));
}
///
function teardown() {
while (targetDiv.firstChild) {
targetDiv.removeChild(targetDiv.firstChild);
}
}
///
var testData;
var sample, sampleData;
function generateTestData() {
testData = {};
for (var i=0; i < (Math.random() * (sample[1]-sample[0])) + sample[0]; i++) {
testData['item'+i] = randomString();
}
}
function randomString()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789";
for( var i=0; i < (Math.random() * (sampleData[1]-sampleData[0])) + sampleData[0]; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function shuffle(arr) {
var len = arr.length;
var i = len;
while (i--) {
var p = parseInt(Math.random()*len);
var t = arr[i];
arr[i] = arr[p];
arr[p] = t;
}
return arr;
};
///
var $targetDiv = $('#targetDiv');
var targetDiv = document.getElementById('targetDiv');
///
function jq() {
var html = [];
var count = 0;
for (var key in testData) {
count += testData[key].length;
html.push('<div>' + testData[key] + '</div>');
}
$targetDiv.html(html.join(''));
return count;
}
function inner() {
var html = [];
var count = 0;
for (var key in testData) {
count += testData[key].length;
html.push('<div>' + testData[key] + '</div>');
}
targetDiv.innerHTML = html.join('');
return count;
}
function dom() {
var root = document.createElement('div');
var node;
var count = 0;
for (var key in testData) {
count += testData[key].length;
node = document.createElement('div');
node.appendChild(document.createTextNode(testData[key]));
root.appendChild(node);
}
targetDiv.appendChild(root);
return count;
}
///
jq.title = 'jQuery .html';
inner.title = 'innerHTML';
dom.title = 'DOM';
///
sample = [10, 100];
sampleData = [100, 1000];
generateTestData();
var duration = 1000;
var testFn = shuffle([jq, inner, dom]);
$.each(testFn, function(k, fn) {
setTimeout(function() { runTest(fn, duration); }, 0);
});
Overall, while each method is more efficient under some conditions (lots of or few data, long or short strings, etc.), the DOM method seems generally faster in all cases.
So, there you have it. Thanks to GGG for the initial test case.
这篇关于最佳实践创建HTML(PHP或jQuery的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!