Tuesday, September 10, 2019

Using Web Worker for Long Tasks in Oracle JET

JavaScript app runs in a single thread. This means if there is a long-running resource-intensive operation - the thread will be blocked and the page will stay frozen until operation completes. Obviously, this is not user-friendly and such behavior should be avoided. We can use Web Workers, through Web Workers we could run long-running operations in separate threads, without blocking the main thread. Code running in Web Worker doesn't have access to UI DOM, this means logic coded in Web Worker should operate with logic which is not directly related to UI.

Sample app contains commented code in dashboard.js. This code blocks main thread for 10 seconds, if you uncomment it - you will see that app becomes frozen for 10 seconds:


Web Worker is defined in dashboard.js. Web Worker is a separate JS file, which is being used for Worker object. API allows to send and receive messages, this way we can communicate to and from Web Worker (start a new task and receive message when task is completed):


Web Worker code - onmessage invoked when the message arrives from the main thread. postMessage sends message back to the main thread:


The sample app is available on GitHub repo.

No comments: