Joelty
Joelty

Reputation: 2009

Web Browser (Chromium/Firefox) becomes unresponsive for 1-2sec after file dialog

How can I improve this code in order to remove unresponsivness / page lag after selecing a file from file dialog and clicking OK?

I've been testing files with sizes around 50-100 KB

function handleFileSelect(evt) {
  var files = evt.target.files; // FileList object

  // files is a FileList of File objects. List some properties.
  var output = [];
  for (var i = 0, f; f = files[i]; i++) {
    output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
      f.size, ' bytes, last modified: ',
      f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
      '</li>');
  }
  document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

I'm running this page on localhost and I'm using SSD

Thanks

Upvotes: 9

Views: 270

Answers (3)

Varun Goel
Varun Goel

Reputation: 475

Your code works and there is nothing wrong with it.You can only improve performance by first measuring it and then taking appropriate actions.

For eg You may refactor the code to a cleaner approach -

let handleFileSelect = (evt) => {
  let files = evt.target.files; // FileList object

  let output = [...files].map((file) => {
    return `<li>
                <strong>${escape(file.name)}</strong> 
                (${file.type || "n/a"}) - ${file.size} bytes,
                 last modified: ${
                   file.lastModifiedDate
                     ? file.lastModifiedDate.toLocaleDateString()
                     : "n/a"
                 }
                </li>`;
  });

  document.getElementById("list").innerHTML = `<ul>${output.join("")}</ul>`;
};

document
  .getElementById("files")
  .addEventListener("change", handleFileSelect, false);
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

Upvotes: 0

shahid jamal
shahid jamal

Reputation: 413

Use Promises in your handleFileSelect function or make async function of it.

Upvotes: 2

Joe - Check out my books
Joe - Check out my books

Reputation: 16925

Your code is perfectly fine. Try measuring the performance to investigate further:


enter image description here

Upvotes: 4

Related Questions