Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importScripts (web workers)

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?

like image 664
Vincent Avatar asked Apr 30 '13 22:04

Vincent


People also ask

What is importScripts?

importScripts() The importScripts() method of the WorkerGlobalScope interface synchronously imports one or more scripts into the worker's scope.

What is a web worker used for?

Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface.

How many web workers can run concurrently?

A web worker is a JavaScript program running on a different thread, in parallel with main thread. The browser creates one thread per tab. The main thread can spawn an unlimited number of web workers, until the user's system resources are fully consumed.

Can web workers import modules?

Both static and dynamic ES module imports are supported in dedicated workers. Chrome and Edge have supported ES modules in shared workers since version 83, but no other browser offers support at this time.


Video Answer


1 Answers

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/

like image 175
dandavis Avatar answered Oct 10 '22 04:10

dandavis