I am currently writing a little library in JavaScript to help me delegate to a web-worker some heavy computation .
For some reasons (mainly for the ability to debug in the UI thread and then run the same code in a worker) I'd like to detect if the script is currently running in a worker or in the UI thread.
I'm not a seasoned JavaScript developper and I would like to ensure that the following function will reliably detect if I'm in a worker or not :
function testenv() {
try{
if (importScripts) {
postMessage("I think I'm in a worker actually.");
}
} catch (e) {
if (e instanceof ReferenceError) {
console.log("I'm the UI thread.");
} else {
throw e;
}
}
}
So, does it ?
Show activity on this post. You should have the web worker post messages about events, like when it is finished work, this way the parent can listen to these messages/events and know when work has completed. The web worker can even post progress events, this is all up to you to build though, it does not come included.
Method 1: Using the typeof operator The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.
You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object.
Quite late to the game on this one, but here's the best, most bulletproofy way I could come up with:
// run this in global scope of window or worker. since window.self = window, we're ok
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
// huzzah! a worker!
} else {
// I'm a window... sad trombone.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With