Assume that we want to pull down some data from the server, Then the data is going to be processed through an array loop, And we are going to build some DOM elements:
Also the action method is like this:
buffer method works like a charm but using
setTimeout is considered to be a bad practice. So that’s where the Web Workers come into play.
So let’s rewrite our example with Web Workers:
As you can see I instantiated a worker, Then I setup an event listener for message, So when data comes in from the AJAX call, we will inject the result into html of a container called
Here you see the worker:
Inside the fetch content we used typical AJAX call because in Web Workers you can not use a third-party library it means that there’s no access to non-thread safe components, So you have to use a native
XMLHttpRequest in your worker. Now if you run the code you will see that now that’s pretty fast even quite a bit faster than before.
You can see the sample code in the GitHub repository