首页 > 解决方案 > 如何消除 chrome 扩展/Firefox 插件弹出的延迟?

问题描述

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

清单.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"});
});

标签: javascriptgoogle-chrome-extensiondownloadpopupfirefox-addon

解决方案


  • 通常 DOM 很慢,所以如果你有很多元素,你应该只显示可见的东西,并在滚动时按需绘制其余的东西。为此有许多库和框架。

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

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

最重要的是,使用devtools profiler而不是猜测。分析结果后,您将看到需要修复/重写的内容。弹出窗口有自己的开发工具(请参阅如何打开它)。


推荐阅读