如何消除 chrome extension/Firefox 附加组件弹出窗口的延迟?

How to remove delay from pop-up of chrome extension/Firefox add-on?

我正在构建 chrome 和 firefox 的批量下载扩展,以下载大量文件。扩展的弹出窗口具有 cancel/pause/resume 功能。下载少量文件时弹出窗口工作正常。但是,当下载大量文件时,弹出菜单需要很长时间才能真正弹出(或者有时根本不会弹出),这可能是因为扩展程序变得非常繁忙并且一次要处理大量文件。有没有办法消除这种延迟?

manifest.json

    "default_popup": "html/popup.html"
  },

popup.html

let bgPage = chrome.extension.getBackgroundPage(); //Getting the variables from the background page

let idsOfDownload = [];
idsOfDownload = bgPage.downloadIds;
console.log(idsOfDownload);

let cancel = document.createElement("button");
cancel.id = "cancel";
cancel.className = "btn";
cancel.innerHTML='<i class="fa fa-stop-circle"></i> Cancel All</button>';
document.body.appendChild(cancel);

$('body').width(350); 

setInterval(function(){

    let downloadString = LZString.decompress(localStorage.getItem('downloadLinks'));

    if(downloadString === "") return;

    let downloadLinks =  JSON.parse(downloadString);

    if (downloadLinks !== undefined && downloadLinks !== null && downloadLinks !== "null") {
        let status = `Total pending download: ${downloadLinks.length}`;
        jQuery("#download-status").html(status);
    }
},1000);


$(cancel).click(function () {
    chrome.runtime.sendMessage({message: "cancel-download"});
});
  • 通常 DOM 很慢,所以如果您有很多元素,您应该只显示可见的内容,并在滚动时根据需要绘制其余内容。为此有很多库和框架。

  • LZString 对于大字符串可能非常慢,因此考虑不使用它或在 web worker 中使用它并通过标准 DOM 消息传递数据。

  • window.localStorage 是同步的,所以如果数据很大,它也可能很慢,考虑切换到异步存储,如 chrome.storage.local 或 IndexedDB。

最重要的,使用devtools profiler instead of guessing. After analyzing the results you'll see what needs fixing/rewriting. The popup has its own devtools (see how to open it).

在我的例子中,弹出窗口很慢,因为我使用的是同步代码块,比如在具有数万个链接的数组上循环,正如@wOxxOm 指出的那样,window.localStorage,这最终阻塞了事件循环.

for loop 替换为 setInterval( //doSomething, 0) 并将 window.localStorage 替换为 chrome.storage.local 在我的情况下有效。