文件对话框后 Web 浏览器 (Chromium/Firefox) 无响应 1-2 秒

从文件对话框中选择文件并单击“确定”后,如何改进此代码以消除无响应/页面延迟?


我一直在测试大小约为 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>

我在本地主机上运行此页面并且使用 SSD



斯蒂芬大帝
浏览 137回答 3
3回答

达令说

你的代码完全没问题。尝试测量性能以进一步调查:

慕村225694

在你的handleFileSelect函数中使用Promises或者让它成为异步函数。

幕布斯7119047

您的代码可以运行并且没有任何问题。您只能通过首先对其进行测量然后采取适当的操作来提高性能。例如,您可以将代码重构为更简洁的方法 -let handleFileSelect = (evt) => {&nbsp; let files = evt.target.files; // FileList object&nbsp; let output = [...files].map((file) => {&nbsp; &nbsp; return `<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <strong>${escape(file.name)}</strong>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (${file.type || "n/a"}) - ${file.size} bytes,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;last modified: ${&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;file.lastModifiedDate&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;? file.lastModifiedDate.toLocaleDateString()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: "n/a"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>`;&nbsp; });&nbsp; document.getElementById("list").innerHTML = `<ul>${output.join("")}</ul>`;};document&nbsp; .getElementById("files")&nbsp; .addEventListener("change", handleFileSelect, false);<input type="file" id="files" name="files[]" multiple /><output id="list"></output>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5