如何从字典中填充大数据列表(约2000项) [英] How to populate a large datalist (~2000 items) from a dictionary

查看:86
本文介绍了如何从字典中填充大数据列表(约2000项)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用以下代码,但是在Chrome上大约需要10秒钟,而在IE11上则需要2分钟,这是最终要用到的地方.

Right now I'm using the following code but it takes ~10 seconds on Chrome and ~2 minutes on IE11, which is where its mostly going to end up being used.

for (var key in dict) {
    if (dict.hasOwnProperty(key)) {
        combo.innerHTML += "<option value=\"" + dict[key] + "\">" + key + "</option>";
    }
}

我正在阅读本教程: http://blog.teamtreehouse.com/creation-autocomplete-dropdowns-datalist-element ,在处理大批量商品时,建议像这样使用ajax,尽管我不确定大商品是指100个商品还是100,000个商品.

I was reading this tutorial: http://blog.teamtreehouse.com/creating-autocomplete-dropdowns-datalist-element which suggested using ajax like so when dealing with larger quantities, though I'm not sure if large refers to 100 items or 100,000 items.

var request = new XMLHttpRequest();

request.onreadystatechange = function(response) {
  if (request.readyState === 4) {
    if (request.status === 200) {

      var jsonOptions = JSON.parse(request.responseText);

      jsonOptions.forEach(function(item) {

        var option = document.createElement('option');
        option.value = item;
        dataList.appendChild(option);

      });

    } else {
      console.log("Failed to load datalist options");
    }
  }
};

request.open('GET', 'html-elements.json', true);
request.send();

我一直在尝试通过将 request.responseText 替换为 JSON.parse(JSON.stringify(dict)); 来使它适用于字典,但是我由于它不在文件中,因此使其开始发出请求时遇到了问题.

I've been trying to get this to work for a dictionary by replacing request.responseText with JSON.parse(JSON.stringify(dict)); but I'm running into problems getting it to make the request to begin with because it's not in a file.

我应该怎么做?如果我不应该为此使用DataList,那么您推荐什么替代方法?

How should I do this? And if I shouldn't be using a DataList for this, what alternative do you recommend?

提前谢谢.

推荐答案

可以提高性能的一个方面是文档片段,因为写入DOM的速度很慢.

One area in which you could speed up performance is with a document fragment as writing to the DOM is slow.

var frag = document.createDocumentFragment();

for (var key in dict) {
    if (dict.hasOwnProperty(key)) {
        var option = document.createElement("OPTION");
        option.textContent = key;
        option.value = dict[key];
        frag.appendChild(option);
    }
}

combo.appendChild(frag);

这篇关于如何从字典中填充大数据列表(约2000项)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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