Last Updated: May 23, 2019
·
2.392K
· fardink

Make use of Web Workers

When it comes to do synchronous stuff like using the LocalStorage or XMLHttpRequest, It's way better to make use of workers to do jobs in a non-blocking manner.

Workers are background tasks that can be easily created and can send messages back to their creators. Creating a worker is as simple as calling the Worker() constructor, specifying a script to be run in the worker thread.
MDN — Worker

Workers can either be written in a different file or within the HTML markup using text/js-worker script type.

e.g.
<script type="text/js-worker"> ... </script>

Workers have access to the same sandbox as the page. So they have access to the same resources like the same Cookie and LocalStorage data or the same location and navigation objects; but as you can guess, no access to the document object, as a worker is actually running in a different thread and is not a document itself.

So, if you have lots of XMLHttpRequests or use the LocalStorage very frequently or against big data, you probably might like to make use of Workers so the browser won't let you down! ;)

Read more

3 Responses
Add your response

AJAX is asynchronous so, it should not block the current thread right? Not sure about LocalStorage, but since its a browser thing (not remote), it should be fast.

I think using web workers in this situation might even slow things down by introducing overheads? Like threads/processes in other languages have associated with them isn't it?

What are your thoughts?

over 1 year ago ·

@jiewmeng I wrote a damn long comment and suddenly deleted it! :D
Long story short:

XMLHttpRequest is mentioned in MDN and I really have no Idea how that works as I've got used to jQuery for the messy stuff!

LocalStorage's API writes all data directly into filesystem, so it has to lock the file. and it's done synchronously.
Of course I'm not talking about a simple application with a single AJAX Request or LocalStorage transaction; but in case of a Facebook like app, you can be waiting seconds for a single transaction or even the browser might crash (as it does in most alike situations)! Let me add that, a file can get locked for different reasons.

Read more in references above and here:
http://www.nczonline.net/blog/2012/03/07/in-defense-of-localstorage/

Regards.

over 1 year ago ·

Now I understand your point of view abit more. I think AJAX is already non-blocking so no need for threading.

I think regarding LocalStorage, seems some kind of async library (eg. async.js) will be better. Reason is looking at WebWorkers API, it looks like its using message passing, which means processes, which have more overhead than threads. Even if its threads, I think its slightly more overhead for a simple task like this requires ... not sure tho.

over 1 year ago ·