Reputation: 1288
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);
click
event listener attached to this button which renders another UI.)Now, most of the stuff is happening in the getData
callback.
When a user clicks on that button. the extension:
a
.a
, I am using a map
on it to create another array b
b
to get another array c
.c
, I call another function that generates the final UI(using values from the array c
)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?
Upvotes: 0
Views: 293
Reputation: 7572
JavaScript is single-threaded. Event loop included - simply, it's just a queue for tasks put into it. If your JS code is actually causing performance issues doing some stuff asynchronously won't help, since then that code will block the event loop anyway.
Only available option is Web workers.
Upvotes: 1