简体   繁体   中英

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

I am building a bulk download extension from chrome and firefox to download a large number of files. The pop up of the extension has the cancel/pause/resume features. The pop up works fine when downloading a small number of files. However, when downloading a larger number of files, the pop-up menu takes forever to actually pop-up (or some time it doesn't whatsoever) probably because the extension becomes very busy and processing a lot of files at a time. Is there a way to eliminate this delay?

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"});
});
  • Generally DOM is slow so if you have a lot of elements you should only display the visible stuff and draw the rest on demand when scrolling. There are many libraries and frameworks for this.

  • LZString can be very slow with big strings so consider not using it or do it inside a web worker and pass the data via standard DOM messaging.

  • window.localStorage is synchronous so it can be slow too if the data is big, consider switching to asynchronous storage like chrome.storage.local or IndexedDB.

Most importantly , use 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 ).

In my case, the pop up was slow because I was using synchronous code blocks like looping over array with tens of thousand links and as @wOxxOm pointed out, window.localStorage , which ended up blocking the event loop.

Replacing for loop with setInterval( //doSomething, 0) and window.localStorage with chrome.storage.local worked in my case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM