2. What is this?
A technology that allows to execute the script in a different context, which does not
block the UI.
What types of workers are exist?
Web Workers
Shared Web Workers
3. Do you know about Service Workers?
That’s a bit different. Service Workers works in a different context, just like the
worker has the same limitations (without access to the DOM). However, this
provides many different api to control web pages.
https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
https://developer.mozilla.org/ru/docs/Web/API/Service_Worker_API
4. How to design a Worker?
var scriptUrl = "/worker.js";
var worker = new Worker(scriptUrl);
var sharedWorker = new SharedWorker(scriptUrl);
// также можно без отдельного скрипта
var blob = new Blob([code], {type:
'application/javascript'});
worker = new Worker(URL.createObjectURL(blob));
5. How to send / receive messages to / from Worker
worker.postMessage({hello: 'world'});
worker.onmessage = m => m.data... ;
sharedWorker.port.postMessage({hello: 'world'});
sharedWorker.port.onmessage = m => m.data... ;
6. How to get a message inside Worker
// in Worker
self.onmessage = function (message) {
message.data ...
};
// in SharedWorker
self.onconnect = function(connect) {
var port = connect.source;
port.onmessage = function(message) {
message.data ...
};
};
https://github.com/MaximYakusik/worker-example/tree/feature/send-hello
7. How to initiate the integration of Workers
worker.postMessage({ port: sharedWorker.port },
[sharedWorker.port]);
8. How to kill worker :)
/*Call in the main thread*/
worker.terminate()
Other options:
- Via the browser api. (in chrome: // inspect)
- Close all pages that use it.
- Ask Shared Worker to close himself.
9. // on worker
self.onconnect = function(connect) {
var port = connect.source;
port.onmessage = function(message) {
switch (message.data.command) {
...
case 'Kill yourself':
port.postMessage('I'm die :(');
self.close();
break;
}
};
};
Closing Shared Worker
//on main
sharedWorker.port
.postMessage({command: 'Kill
yourself'});
https://github.com/MaximYakusik/worker-example/tree/feature/worker-must-die
10. What could I use it for?
For resource-intensive tasks such as packing and unpacking of archives.
https://gildas-lormeau.github.io/zip.js/
11. In which browsers can I use it?
https://caniuse.com/#feat=webworkers,sharedworkers