Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  41] [ 2]  / answers: 1 / hits: 59739  / 11 Years ago, tue, april 30, 2013, 12:00:00

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?


More From » html

 Answers
6

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/


[#78500] Monday, April 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marint

Total Points: 550
Total Questions: 105
Total Answers: 124

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
;