Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  46] [ 7]  / answers: 1 / hits: 18262  / 13 Years ago, fri, october 28, 2011, 12:00:00

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 ?


More From » web-worker

 Answers
2

As noted there is an answer in another thread which says to check for the presence of a document object on the window. I wanted to however make a modification to your code to avoid doing a try/catch block which slows execution of JS in Chrome and likely in other browsers as well.



EDIT: I made an error previously in assuming there was a window object in the global scope. I usually add



//This is likely SharedWorkerContext or DedicatedWorkerContext
window=this;


to the top of my worker loader script this allows all functions that use window feature detection to not blow up. Then you may use the function below.



function testEnv() {
if (window.document === undefined) {
postMessage(I'm fairly confident I'm a webworker);
} else {
console.log(I'm fairly confident I'm in the renderer thread);
}
}


Alternatively without the window assignment as long as its at top level scope.



var self = this;
function() {
if(self.document === undefined) {
postMessage(I'm fairly confident I'm a webworker);
} else {
console.log(I'm fairly confident I'm in the renderer thread);
}
}

[#89397] Thursday, October 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marinal

Total Points: 655
Total Questions: 99
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;