importScripts (web workers)

Vincent picture Vincent · May 1, 2013 · Viewed 43.9k times · Source

I have tried to use importScripts to load a second JavaScript file into my web worker, but although no error occurred, it didn't work. I narrowed the problem down to this very simple situation:

In the main HTML file:

<script>
var w = new Worker("script1.js");
w.addEventListener("message", function(e){
    alert(e.data);
})
w.postMessage();
</script>

In script1.js:

self.addEventListener("message", function(e){
    var a = 5;
    importScripts("script2.js");
    self.postMessage(a);
})

In script2.js:

a = 6

I would like to see a dialog displaying 6, because a was changed from 5 to 6 by importing script2.js, but the dialog shows 5. What am I missing here?

Answer

dandavis picture dandavis · May 1, 2013

Using var a in the function means that a will always be private. Since importScripts adds to the global scope, JS prefers to access the more localized a in the function that posts a. You can post self.a instead, which shall be 6, as you expected.

EDIT: Someone recently asked me about this in person, so I made a demo to clarify the behaviour: http://pagedemos.com/importscript/