1
0
mirror of https://github.com/onkelbeh/cheatsheets.git synced 2025-06-15 14:47:53 +02:00
cheatsheets/web-workers.md
Rico Sta. Cruz 511de900ba
Formatting updates (#2133)
- Update some sheets which have very long sections
- Remove `layout: 2017/sheet` (everything has the same layout now)
- Remove outdated sheets
2024-04-03 18:30:24 +11:00

59 lines
1.0 KiB
Markdown

---
title: Web workers
category: JavaScript
updated: 2017-10-30
weight: -1
---
## Web workers
#### Client
```js
var worker = new Worker('worker.js')
worker.onmessage = function (message) {
alert(JSON.stringify(message.data))
})
worker.postMessage('hello!')
```
Messages can be anything that can be serialized into JSON (objects, arrays, strings, numbers, booleans). See: [structured clone](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)
#### Worker
```js
self.onmessage = function (message) {
···
}
self.postMessage({ msg: 'hello' })
```
### Message data
#### [MessageEvent]
```js
bubbles: false
cancelBubble: false
cancelable: false
clipboardData: undefined
currentTarget: Worker
data: "Hello" the data
defaultPrevented: false
eventPhase: 0
lastEventId: ""
origin: ""
ports: Array[0]
returnValue: true
source: null
srcElement: Worker
target: Worker
timeStamp: 1344821022383
type: "message"
```
These are the contents of `message` on onmessage.