I am learning to develop chrome extensions(and at the same time learning javascript as well). I am experimenting with an extension that runs on youtube webpage. The thing is when I scroll, sometimes the webpage kinda feels a little jittery.
So, I started looking for possible reasons. I came across a few good videos including "what the heck is event loop by Philip Roberts" in which he talked about event loop and other related stuff. This made me wonder if it's because of this very reason the webpage feels jittery.
The code in the content script is synchronous and I don't have much experience with asynchronous coding in javascript. Concepts like promises, async/await are new to me.
Here is the code in the content script at a very high level.
chrome.storage.sync.get(); // getting some data here
let activateButton = document.createElement("div");
activateButton.id = "activate-ext";
activateButton.addEventListener("click", getData);
- there is a call to chrome storage api
- some code to render a button(there is a
clickevent listener attached to this button which renders another UI.) - then I added this button to the dom
Now, most of the stuff is happening in the getData callback.
When a user clicks on that button. the extension:
- retrieve data from the webpage and does some regex matching and then the string values that I want is stored in an array
a. - then when I have the array
a, I am using amapon it to create another arrayb - then another operation on all the elements of
bto get another arrayc. - and now finally when I have the array
c, I call another function that generates the final UI(using values from the arrayc)
This is how getData looks like:
function getdata(){
const regex = /some_regex/g;
let match = regex.exec(data);
while (match) {
a.push(match[index]);
match = regex.exec(description)
}
b = createAnotherArray(a) // this function returns array b
c = anotherOperation(b)
generateUI(c) // in this function I am rendering the UI
}
Now, all this code is synchronous(apart from the call to chrome storage API and some callbacks) and I believe some of these operations(like regex matching) take time which blocks the event loop.
So what would be the best way to restructure this whole code using promises(async/await) so it does not block the browser from rendering/updating UI.
I also saw some loops with async/await and I too have loops in my code too. So, do I need to do that too?
regex.execinto async code is to stick it in a worker thread, which will almost certainly be more effort than it's worth. If your webpage is feeling jittery it's because you're running some code way too often - consider caching results or caching references to buttons or whatever else is being done way too often.