Tips for populating a dictionary with a large datalist of around 2000 items

Currently, I'm facing an issue where the code I'm using takes about 10 seconds to run on Chrome and around 2 minutes on IE11, which is the primary browser it will be used with.

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

I came across a tutorial at , recommending the use of ajax for dealing with larger datasets. However, the definition of 'large' is not clear - could it mean 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();

I've been trying to adapt this approach for a dictionary by replacing request.responseText with

JSON.parse(JSON.stringify(dict));
. However, I'm encountering issues as the data is not stored in a file, making it difficult to make the request from the server. Any suggestions on how to proceed? And if a DataList isn't suitable for this purpose, what alternative would you recommend?

Appreciate any advice in advance.

Answer №1

To optimize performance, consider using a document fragment for faster DOM manipulation.

var fragment = document.createDocumentFragment();

for (var property in data) {
    if (data.hasOwnProperty(property)) {
        var element = document.createElement("DIV");
        element.textContent = property;
        element.value = data[property];
        fragment.appendChild(element);
    }
}

container.appendChild(fragment);

Answer №2

If you want to improve performance, consider constructing the HTML string first and then setting it as innerHTML.

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

By following this method, you can see a significant difference in performance: http://jsperf.com/string-append-vs-dom

Answer №3

The performance of the DOM is commonly criticized for being slow. To improve speed, consider manually filtering and displaying only a set number of initial elements. Additionally, utilizing document fragments, as suggested by znap026, can also contribute to enhancing efficiency.

"use strict";

var data = Object.getOwnPropertyNames(window).sort(),
  datalist = document.getElementById("datalist"),
  input = document.getElementById("input");
  
const processedData = Object.fromEntries(data.map(d => [d.toLowerCase(), d]));

function search() {
  var term = input.value.toLowerCase();
  var found = 0;
  var frag = document.createDocumentFragment();

  for (var child of [].slice.apply(datalist.childNodes)) {
    datalist.removeChild(child);
  }

  for (var searchable in processedData) {
    if (searchable.indexOf(term) === 0) {
      let item = processedData[searchable];
      let option = document.createElement("option");
      option.value = item

      frag.appendChild(option);
      if (++found > 10) break;
    }
  }

  datalist.appendChild(frag);
}

search();
input.addEventListener("input", search);
<input id="input" list="datalist" placeholder="window properties"/>
<datalist id="datalist"></datalist>

Answer №4

To enhance performance, one technique is to disconnect the datalist from the input element and then reconnect it after filling it with data:

"use strict";

// initialize
const items = Object.getOwnPropertyNames(window);
const dataList = document.getElementById("datalist");
const options = items.map(key => new Option(key));

let startTime = performance.now();
dataList.replaceChildren(...options);
console.log('simple replace:', performance.now() - startTime);

// reset
dataList.replaceChildren(...[]);

startTime = performance.now();
dataList.setAttribute("id", undefined);
dataList.replaceChildren(...options);
dataList.setAttribute("id", "datalist");
console.log('replace with detach and attach:', performance.now() - startTime);
<input list="datalist" />
<datalist id="datalist"></datalist>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to determine the total scrollable height of the browser's scroll bars?

I understand that $(window).scrollTop() provides the current position of the browser scroll bar, but how can I determine the total scrollable area? For example, if I scroll to the bottom and $(window).scrollTop() equals 300px, scrolling back to the top se ...

Mastering the art of debugging a mongoose action in node.js

I am utilizing mongoose for connecting my node.js app with mongoDB. However, I am facing an issue where the database does not get updated when I create or update a model instance. How can I effectively debug and identify what goes wrong in the create or up ...

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

Using React.js to establish a connection with a database

Can someone help me with connecting my reactjs to mysql? I have already installed mysql and followed the usual instructions, but I keep getting an error "TypeError: mysql.createConnection is not a function". Below are the codes I am working with. import ...

Creating a Cross Fade Animation effect with the combination of CSS and JavaScript

I've been attempting to create a similar animation using html and css. Below gif shows the desired outcome I am aiming for: https://i.sstatic.net/YsNGy.gif Although I have tried the following code, I have not been able to achieve the desired result ...

Android textView is populated with randomly generated alphanumeric text after parsing file

I have a parse file coming from parse.com as a string message, and I need to display it in a textView. ParseFile file = message.getParseFile(ParseConstants.KEY_FILE); String filePath = file.getDataInBackground().toString(); if (messageTy ...

The shadow effects and color overlays do not seem to be functioning properly in Mozilla Firefox

I have designed a popup registration form using the Bootstrap modal class. To ensure form validation, I have integrated some jQuery validation engine functionality. Additionally, I customized the appearance by adding a box shadow, adjusting the background ...

Generating HTML using a filter

I have been working on creating a filter that will render HTML tags. Here is the code for my filter: filters: { limitStrLength: function (value, maxLength) { if (value && value.length > maxLength) { let partialVal = value.substr(0, ...

Transferring a JavaScript variable to C# to execute an SQL SELECT query, then sending the returned result back to JavaScript

I am facing an issue while trying to execute code in my Code Behind to query my SQL Server using a JavaScript variable and then return the result as an Integer back to my Javascript. My approach involves running some Javascript code initially to obtain a ...

Encounter an error parsing the package.json file. Confirmed that it is valid JSON

As I embark on creating my very first yeoman generator, I have encountered an issue when running yo to initiate the project. The error message I am receiving is as follows: npm ERR! install Couldn't read dependencies npm ERR! Darwin 14.0.0 npm ERR! a ...

What is the optimal level of safety logic to incorporate into my proprietary components?

Having developed numerous React components, setting propTypes, writing tests, and occasionally defining default props, I find myself pondering the balance between safety and efficiency. Experimenting with Flow types has led me to consider implementing addi ...

Error: The request was denied by the operating system. Issue encountered while attempting to build a new React application

I recently installed the LTS version 14.17.3 of Node (npm version 6.14.13). Following that, I successfully globally installed create-react-app using the command "npm install -g create-react-app" (version 4.0.3). However, when attempting to create a new R ...

What is preventing me from obtaining the select and input values?

I'm currently facing an issue where I am unable to retrieve the values of customInput and customSelect and store them in the state. The challenge arises when trying to integrate these components into a react dashboard material-ui setup. Strangely, whe ...

In order to enhance user experience, I would like the tabs of the dropdown in the below example to be activated by

function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } ...

Is there a way to create animated CSS box-shadow depth using jQuery or CSS3 transitions?

This code snippet applies delays but doesn't seem to update the style changes until the loop completes: for (i=20;i>=0;i--) { var boxShadow = i+"px "+i+"px "+i+"px #888"; $('article').css("box-shadow", boxShadow); ...

Trigger a personalized URL while making an ajax call

I was attempting to run an AJAX request (file: ajax.php) and desire to trigger another custom URL from ajax.php while the AJAX call is in progress. I experimented with CURL for this purpose, but unfortunately, it did not yield favorable results. If someo ...

Enhance your <head> section by adding lines when utilizing Layouts within Iron Router

Is there a way to add more lines to the <head> section using Iron Router and layouts? Take for example, inserting the following code snippet into the <head>... <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=ed ...

Express.js session management -- Ensuring sessions are created exclusively for authenticated users

I've implemented the express-session Node module to handle secure session cookies. // To ensure certain requests require an active session, this code sets up a secure session cookie app.use(expressSession({ secret: "wouldn'tyouliketoknow", ...

List of null variables

I'm having trouble grasping the concept of an array filled with empty values like this: let arr=[,,,]; When I attempt to log the length, it shows 3 instead of 4. let arr=[,,,]; console.log('length',arr.length); console.log('arr[1]&a ...

Are mutations in Vuex guaranteed to be atomic?

I'm currently investigating the atomicity of mutations in Vuex. The code snippet I'm reviewing has me questioning whether the CHANGE_A mutation could potentially be triggered while CHANGE_B is still in progress: const mutations = { [CHANGE_A]( ...