-
Notifications
You must be signed in to change notification settings - Fork 1
/
15248840485977.html
739 lines (475 loc) · 32.1 KB
/
15248840485977.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>
The Basics of Web Workers - HTML5 Rocks - Junkman
</title>
<link href="atom.xml" rel="alternate" title="Junkman" type="application/atom+xml">
<link rel="stylesheet" href="asset/css/foundation.min.css" />
<link rel="stylesheet" href="asset/css/docs.css" />
<script src="asset/js/vendor/modernizr.js"></script>
<script src="asset/js/vendor/jquery.js"></script>
<script src="asset/highlightjs/highlight.pack.js"></script>
<link href="asset/highlightjs/styles/github.css" media="screen, projection" rel="stylesheet" type="text/css">
<script>hljs.initHighlightingOnLoad();</script>
<script type="text/javascript">
function before_search(){
var searchVal = 'site:panlw.github.io ' + document.getElementById('search_input').value;
document.getElementById('search_q').value = searchVal;
return true;
}
</script>
</head>
<body class="antialiased hide-extras">
<div class="marketing off-canvas-wrap" data-offcanvas>
<div class="inner-wrap">
<nav class="top-bar docs-bar hide-for-small" data-topbar>
<section class="top-bar-section">
<div class="row">
<div style="position: relative;width:100%;"><div style="position: absolute; width:100%;">
<ul id="main-menu" class="left">
<li id=""><a target="self" href="index.html">Home</a></li>
<li id=""><a target="_self" href="archives.html">Archives</a></li>
</ul>
<ul class="right" id="search-wrap">
<li>
<form target="_blank" onsubmit="return before_search();" action="http://google.com/search" method="get">
<input type="hidden" id="search_q" name="q" value="" />
<input tabindex="1" type="search" id="search_input" placeholder="Search"/>
</form>
</li>
</ul>
</div></div>
</div>
</section>
</nav>
<nav class="tab-bar show-for-small">
<a href="javascript:void(0)" class="left-off-canvas-toggle menu-icon">
<span> Junkman</span>
</a>
</nav>
<aside class="left-off-canvas-menu">
<ul class="off-canvas-list">
<li><a href="index.html">HOME</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="about.html">ABOUT</a></li>
<li><label>Categories</label></li>
<li><a href="Infra.html">Infra</a></li>
<li><a href="Coding.html">Coding</a></li>
<li><a href="Modeling.html">Modeling</a></li>
<li><a href="Archtecting.html">Archtecting</a></li>
</ul>
</aside>
<a class="exit-off-canvas" href="#"></a>
<section id="main-content" role="main" class="scroll-container">
<script type="text/javascript">
$(function(){
$('#menu_item_index').addClass('is_active');
});
</script>
<div class="row">
<div class="large-8 medium-8 columns">
<div class="markdown-body article-wrap">
<div class="article">
<h1>The Basics of Web Workers - HTML5 Rocks</h1>
<div class="read-more clearfix">
<span class="date">2018/4/28</span>
<span>posted in </span>
<span class="posted-in"><a href='Node.js.html'>Node.js</a></span>
<span class="comments">
</span>
</div>
</div><!-- article -->
<div class="article-content">
<blockquote>
<p><a href="https://www.html5rocks.com/en/tutorials/workers/basics/">https://www.html5rocks.com/en/tutorials/workers/basics/</a></p>
<p>Eric Bidelman, July 26th, 2010</p>
</blockquote>
<h2 id="toc_0">The Problem: JavaScript Concurrency</h2>
<p>There are a number of bottlenecks preventing interesting applications from being ported (say, from server-heavy implementations) to client-side JavaScript. Some of these include browser compatibility, static typing, accessibility, and performance. Fortunately, the latter is quickly becoming a thing of the past as browser vendors rapidly improve the speed of their JavaScript engines.</p>
<p>One thing that's remained a hindrance for JavaScript is actually the language itself. JavaScript is a single-threaded environment, meaning multiple scripts cannot run at the same time. As an example, imagine a site that needs to handle UI events, query and process large amounts of API data, and manipulate the DOM. Pretty common, right? Unfortunately all of that can't be simultaneous due to limitations in browsers' JavaScript runtime. Script execution happens within a single thread.</p>
<p>Developers mimic 'concurrency' by using techniques like <code>setTimeout()</code>, <code>setInterval()</code>, <code>XMLHttpRequest</code>, and event handlers. Yes, all of these features run asynchronously, but non-blocking doesn't necessarily mean concurrency. Asynchronous events are processed after the current executing script has yielded. The good news is that HTML5 gives us something better than these hacks!</p>
<h2 id="toc_1">Introducing Web Workers: Bring Threading to JavaScript</h2>
<p>The <a href="http://www.whatwg.org/specs/web-workers/current-work/">Web Workers</a> specification defines an API for spawning background scripts in your web application. Web Workers allow you to do things like fire up long-running scripts to handle computationally intensive tasks, but without blocking the UI or other scripts to handle user interactions. They're going to help put and end to that nasty 'unresponsive script' dialog that we've all come to love:</p>
<p><img src="/static/images/screenshots/workers/unresponsive_script.gif" alt="Unresponsive script dialog" title="Unresponsive script dialog"/> Common unresponsive script dialog.</p>
<p>Workers utilize thread-like message passing to achieve parallelism. They're perfect for keeping your UI refresh, performant, and responsive for users.</p>
<h3 id="toc_2">Types of Web Workers</h3>
<p>It's worth noting that the <a href="http://www.whatwg.org/specs/web-workers/current-work/">specification</a> discusses two kinds of Web Workers, <a href="http://www.whatwg.org/specs/web-workers/current-work/#dedicated-workers-and-the-worker-interface">Dedicated Workers</a> and <a href="http://www.whatwg.org/specs/web-workers/current-work/#sharedworker">Shared Workers</a>. This article will only cover dedicated workers and I'll refer to them as 'web workers' or 'workers' throughout.</p>
<h2 id="toc_3">Getting Started</h2>
<p>Web Workers run in an isolated thread. As a result, the code that they execute needs to be contained in a separate file. But before we do that, the first thing to do is create a new <code>Worker</code> object in your main page. The constructor takes the name of the worker script:</p>
<pre><code class="language-js">var worker = new Worker('task.js');
</code></pre>
<p>If the specified file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. The worker will not begin until the file has completely downloaded and executed. If the path to your worker returns an 404, the worker will fail silently.</p>
<p>After creating the worker, start it by calling the <code>postMessage()</code> method:</p>
<pre><code class="language-js">worker.postMessage(); // Start the worker.
</code></pre>
<h3 id="toc_4">Communicating with a Worker via Message Passing</h3>
<p>Communication between a work and its parent page is done using an event model and the <code>postMessage()</code> method. Depending on your browser/version, <code>postMessage()</code> can accept either a string or JSON object as its single argument. The latest versions of the modern browsers support passing a JSON object.</p>
<p>Below is a example of using a string to pass 'Hello World' to a worker in doWork.js. The worker simply returns the message that is passed to it.</p>
<p>Main script:</p>
<pre><code class="language-js">var worker = new Worker('doWork.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.
</code></pre>
<p>doWork.js (the worker):</p>
<pre><code class="language-js">self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
</code></pre>
<p>When <code>postMessage()</code> is called from the main page, our worker handles that message by defining an <code>onmessage</code> handler for the <code>message</code> event. The message payload (in this case 'Hello World') is accessible in <code>Event.data</code>. Although this particular example isn't very exciting, it demonstrates that <code>postMessage()</code> is also your means for passing data back to the main thread. Convenient!</p>
<p>Messages passed between the main page and workers are copied, not shared. For example, in the next example the 'msg' property of the JSON message is accessible in both locations. It appears that the object is being passed directly to the worker even though it's running in a separate, dedicated space. In actuality, what is happening is that the object is being serialized as it's handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each pass. Most browsers implement this feature by automatically JSON encoding/decoding the value on either end.</p>
<p>The following is a more complex example that passes messages using JSON objects.</p>
<p>Main script:</p>
<pre><code class="language-js"><button onclick="sayHI()">Say HI</button>
<button onclick="unknownCmd()">Send unknown command</button>
<button onclick="stop()">Stop worker</button>
<output id="result"></output>
<script>
function sayHI() {
worker.postMessage({'cmd': 'start', 'msg': 'Hi'});
}
function stop() {
// worker.terminate() from this script would also stop the worker.
worker.postMessage({'cmd': 'stop', 'msg': 'Bye'});
}
function unknownCmd() {
worker.postMessage({'cmd': 'foobard', 'msg': '???'});
}
var worker = new Worker('doWork2.js');
worker.addEventListener('message', function(e) {
document.getElementById('result').textContent = e.data;
}, false);
</script>
</code></pre>
<p>doWork2.js:</p>
<pre><code class="language-js">self.addEventListener('message', function(e) {
var data = e.data;
switch (data.cmd) {
case 'start':
self.postMessage('WORKER STARTED: ' + data.msg);
break;
case 'stop':
self.postMessage('WORKER STOPPED: ' + data.msg +
'. (buttons will no longer work)');
self.close(); // Terminates the worker.
break;
default:
self.postMessage('Unknown command: ' + data.msg);
};
}, false);
</code></pre>
<p><strong>Note</strong>: There are two ways to stop a worker: by calling <code>worker.terminate()</code> from the main page or by calling <code>self.close()</code> inside of the worker itself.</p>
<p><strong>Example</strong>: Run this worker!</p>
<p><button onclick="sayHI()">Say HI</button> <button onclick="unknownCmd()">Send unknown command</button> <button onclick="stop()">Stop worker</button></p>
<h2 id="toc_5">Transferrable objects</h2>
<p>Most browsers implement the <a href="http://updates.html5rocks.com/2011/09/Workers-ArrayBuffer">structured cloning</a> algorithm, which allows you to pass more complex types in/out of Workers such as <code>File</code>, <code>Blob</code>, <code>ArrayBuffer</code>, and JSON objects. However, when passing these types of data using <code>postMessage()</code>, a copy is still made. Therefore, if you're passing a large 50MB file (for example), there's a noticeable overhead in getting that file between the worker and the main thread.</p>
<p>Structured cloning is great, but a copy can take hundreds of milliseconds. To combat the perf hit, you can use <a href="http://www.w3.org/html/wg/drafts/html/master/infrastructure.html#transferable-objects">Transferable Objects</a>.</p>
<p>With Transferable Objects, data is transferred from one context to another. It is zero-copy, which vastly improves the performance of sending data to a Worker. Think of it as pass-by-reference if you're from the C/C++ world. However, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred to the new context. For example, when transferring an ArrayBuffer from your main app to Worker, the original <code>ArrayBuffer</code> is cleared and no longer usable. Its contents are (quiet literally) transferred to the Worker context.</p>
<p>To use transferrable objects, use a slightly different signature of <code>postMessage()</code>:</p>
<pre><code class="language-js">worker.postMessage(arrayBuffer, [arrayBuffer]);
window.postMessage(arrayBuffer, targetOrigin, [arrayBuffer]);
</code></pre>
<p>The worker case, the first argument is the data and the second is the list of items that should be transferred. The first argument doesn't have to be an <code>ArrayBuffer</code> by the way. For example, it can be a JSON object:</p>
<pre><code class="language-js">worker.postMessage({data: int8View, moreData: anotherBuffer},
[int8View.buffer, anotherBuffer]);
</code></pre>
<p>The important point being: the second argument must be an array of <code>ArrayBuffer</code>s. This is your list of transferrable items.</p>
<p>To see the speed improvement of transferrables, check out this <a href="http://html5-demos.appspot.com/static/workers/transferables/index.html">DEMO</a>. For more information on transferrables, see our <a href="http://updates.html5rocks.com/2011/12/Transferable-Objects-Lightning-Fast">HTML5Rock post</a>.</p>
<h2 id="toc_6">The Worker Environment</h2>
<h3 id="toc_7">Worker Scope</h3>
<p>In the context of a worker, both <code>self</code> and <code>this</code> reference the global scope for the worker. Thus, the previous example could also be written as:</p>
<pre><code class="language-js">addEventListener('message', function(e) {
var data = e.data;
switch (data.cmd) {
case 'start':
postMessage('WORKER STARTED: ' + data.msg);
break;
case 'stop':
...
}, false);
</code></pre>
<p>Alternatively, you could set the <code>onmessage</code> event handler directly (though <code>addEventListener</code> is always encouraged by JavaScript ninjas).</p>
<pre><code class="language-js">onmessage = function(e) {
var data = e.data;
...
};
</code></pre>
<h3 id="toc_8">Features Available to Workers</h3>
<p>Due to their multi-threaded behavior, web workers only has access to a subset of JavaScript's features:</p>
<ul>
<li> The <code>navigator</code> object</li>
<li> The <code>location</code> object (read-only)</li>
<li> <code>XMLHttpRequest</code></li>
<li> <code>setTimeout()/clearTimeout()</code> and <code>setInterval()/clearInterval()</code></li>
<li> The <a href="/tutorials/appcache/beginner/">Application Cache</a></li>
<li> Importing external scripts using the <code>importScripts()</code> method</li>
<li> <a href="#toc-enviornment-subworkers">Spawning other web workers</a></li>
</ul>
<p>Workers do NOT have access to:</p>
<ul>
<li> The DOM (it's not thread-safe)</li>
<li> The <code>window</code> object</li>
<li> The <code>document</code> object</li>
<li> The <code>parent</code> object</li>
</ul>
<h3 id="toc_9">Loading External Scripts</h3>
<p>You can load external script files or libraries into a worker with the <code>importScripts()</code> function. The method takes zero or more strings representing the filenames for the resources to import.</p>
<p>This example loads <code>script1.js</code> and <code>script2.js</code> into the worker:</p>
<p>worker.js:</p>
<pre><code class="language-js">importScripts('script1.js');
importScripts('script2.js');
</code></pre>
<p>Which can also be written as a single import statement:</p>
<pre><code class="language-js">importScripts('script1.js', 'script2.js');
</code></pre>
<h3 id="toc_10">Subworkers</h3>
<p>Workers have the ability to spawn child workers. This is great for further breaking up large tasks at runtime. However, subworkers come with a few caveats:</p>
<ul>
<li> Subworkers must be hosted within the same origin as the parent page.</li>
<li> URIs within subworkers are resolved relative to their parent worker's location (as opposed to the main page).</li>
</ul>
<p>Keep in mind most browsers spawn separate processes for each worker. Before you go spawning a worker farm, be cautious about hogging too many of the user's system resources. One reason for this is that messages passed between main pages and workers are copied, not shared. See <a href="#toc-gettingstarted-workercomm">Communicating with a Worker via Message Passing</a>.</p>
<p>For an sample of how to spawn a subworker, see <a href="http://www.whatwg.org/specs/web-workers/current-work/#delegation">the example</a> in the specification.</p>
<h2 id="toc_11">Inline Workers</h2>
<p>What if you want to create your worker script on the fly, or create a self-contained page without having to create separate worker files? With <code>Blob()</code>, you can "inline" your worker in the same HTML file as your main logic by creating a URL handle to the worker code as a string:</p>
<pre><code class="language-js">var blob = new Blob(["onmessage = function(e) { postMessage('msg from worker'); }"]);
// Obtain a blob URL reference to our worker 'file'.
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
worker.onmessage = function(e) {
// e.data == 'msg from worker'
};
worker.postMessage(); // Start the worker.
</code></pre>
<h3 id="toc_12">Blob URLs</h3>
<p>The magic comes with the call to <a href="http://dev.w3.org/2006/webapi/FileAPI/#dfn-createObjectURL"><code>window.URL.createObjectURL()</code></a>. This method creates a simple URL string which can be used to reference data stored in a DOM <code>File</code> or <code>Blob</code> object. For example:</p>
<pre><code class="language-js">blob:http://localhost/c745ef73-ece9-46da-8f66-ebes574789b1
</code></pre>
<p>Blob URLs are unique and last for the lifetime of your application (e.g. until the <code>document</code> is unloaded). If you're creating many Blob URLs, it's a good idea to release references that are no longer needed. You can explicitly release a Blob URLs by passing it to <a href="http://dev.w3.org/2006/webapi/FileAPI/#dfn-revokeObjectURL"><code>window.URL.revokeObjectURL()</code></a>:</p>
<pre><code class="language-js">window.URL.revokeObjectURL(blobURL);
</code></pre>
<p>In Chrome, there's a nice page to view all of the created blob URLs: <code>chrome://blob-internals/</code>.</p>
<h3 id="toc_13">Full Example</h3>
<p>Taking this one step further, we can get clever with how the worker's JS code is inlined in our page. This technique uses a <code><script></code> tag to define the worker:</p>
<pre><code class="language-js"><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="log"></div>
<script id="worker1" type="javascript/worker">
// This script won't be parsed by JS engines
// because its type is javascript/worker.
self.onmessage = function(e) {
self.postMessage('msg from worker');
};
// Rest of your worker code goes here.
</script>
<script>
function log(msg) {
// Use a fragment: browser will only render/reflow once.
var fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode(msg));
fragment.appendChild(document.createElement('br'));
document.querySelector("#log").appendChild(fragment);
}
var blob = new Blob([document.querySelector('#worker1').textContent]);
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
log("Received: " + e.data);
}
worker.postMessage(); // Start the worker.
</script>
</body>
</html>
</code></pre>
<p>In my opinion, this new approach is a bit cleaner and more legible. It defines a script tag with <var>id="worker1"</var> and <var>type='javascript/worker'</var> (so the browser doesn't parse the JS). That code is extracted as a string using <code>document.querySelector('#worker1').textContent</code> and passed to <code>Blob()</code> to create the file.</p>
<h3 id="toc_14">Loading External Scripts</h3>
<p>When using these techniques to inline your worker code, <code>importScripts()</code> will only work if you supply an absolute URI. If you attempt to pass a relative URI, the browser will complain with a security error. The reason being: the worker (now created from a blob URL) will be resolved with a <code>blob:</code> prefix, while your app will be running from a different (presumably <code>http://</code>) scheme. Hence, the failure will be due to cross origin restrictions.</p>
<p>One way to utilize <code>importScripts()</code> in an inline worker is to "inject" the current url of your main script is running from by passing it to the inline worker and constructing the absolute URL manually. This will insure the external script is imported from the same origin. Assuming your main app is running from <a href="http://example.com/index.html">http://example.com/index.html</a>:</p>
<pre><code class="language-js">...
<script id="worker2" type="javascript/worker">
self.onmessage = function(e) {
var data = e.data;
if (data.url) {
var url = data.url.href;
var index = url.indexOf('index.html');
if (index != -1) {
url = url.substring(0, index);
}
importScripts(url + 'engine.js');
}
...
};
</script>
<script>
var worker = new Worker(window.URL.createObjectURL(bb.getBlob()));
worker.postMessage(**{url: document.location}**);
</script>
</code></pre>
<h2 id="toc_15">Handling Errors</h2>
<p>As with any JavaScript logic, you'll want to handle any errors that are thrown in your web workers. If an error occurs while a worker is executing, the an <code>ErrorEvent</code> is fired. The interface contains three useful properties for figuring out what went wrong: <code>filename</code> - the name of the worker script that caused the error, <code>lineno</code> - the line number where the error occurred, and <code>message</code> - a meaningful description of the error. Here is an example of setting up an <code>onerror</code> event handler to print the properties of the error:</p>
<pre><code class="language-js"><output id="error" style="color: red;"></output>
<output id="result"></output>
<script>
function onError(e) {
document.getElementById('error').textContent = [
'ERROR: Line ', e.lineno, ' in ', e.filename, ': ', e.message
].join('');
}
function onMsg(e) {
document.getElementById('result').textContent = e.data;
}
var worker = new Worker('workerWithError.js');
worker.addEventListener('message', onMsg, false);
worker.addEventListener('error', onError, false);
worker.postMessage(); // Start worker without a message.
</script>
</code></pre>
<p><strong>Example</strong>: workerWithError.js tries to perform 1/x, where x is undefined.</p>
<p><button onclick="startErrorWorker()">Run it</button></p>
<p>workerWithError.js:</p>
<pre><code class="language-js">self.addEventListener('message', function(e) {
postMessage(1/x); // Intentional error.
};
</code></pre>
<h2 id="toc_16">A Word on Security</h2>
<h3 id="toc_17">Restrictions with Local Access</h3>
<p>Due to Google Chrome's security restrictions, workers will not run locally (e.g. from <code>file://</code>) in the latest versions of the browser. Instead, they fail silently! To run your app from the <code>file://</code> scheme, run Chrome with the <code>--allow-file-access-from-files</code> flag set. <strong>NOTE</strong>: It is not recommended to run your primary browser with this flag set. It should only be used for testing purposes and not regular browsing.</p>
<p>Other browsers do not impose the same restriction.</p>
<h3 id="toc_18">Same Origin Considerations</h3>
<p>Worker scripts must be external files with the same scheme as their calling page. Thus, you cannot load a script from a <code>data:</code> URL or <code>javascript:</code> URL, and an <code>https:</code> page cannot start worker scripts that begin with <code>http:</code> URLs.</p>
<h2 id="toc_19">Use Cases</h2>
<p>So what kind app would utilize web workers? Unfortunately, web workers are still relatively new and the majority of samples/tutorials out there involve computing prime numbers. Although that isn't very interesting, it's useful for understanding the concepts of web workers. Here are a few more ideas to get your brain churning:</p>
<ul>
<li> Prefetching and/or caching data for later use</li>
<li> Code syntax highlighting or other real-time text formatting</li>
<li> Spell checker</li>
<li> Analyzing video or audio data</li>
<li> Background I/O or polling of webservices</li>
<li> Processing large arrays or humungous JSON responses</li>
<li> Image filtering in <code><canvas/></code></li>
<li> Updating many rows of a local web database</li>
</ul>
<h2 id="toc_20">Demos</h2>
<ul>
<li> Example from <a href="http://slides.html5rocks.com/#web-workers">HTML5Rocks slides</a></li>
<li> <a href="http://htmlfive.appspot.com/static/tracker1.html">Motion tracker</a></li>
<li> <a href="http://people.mozilla.com/%7Eprouget/demos/worker_and_simulatedannealing/index.xhtml">Simulated Annealing</a></li>
<li> <a href="http://html5demos.com/worker">HTML5demos sample</a></li>
</ul>
<h2 id="toc_21">References</h2>
<ul>
<li> <a href="http://www.whatwg.org/specs/web-workers/current-work/">Web Workers</a> specification</li>
<li> <a href="http://developer.mozilla.org/en/Using_web_workers">"Using web workers"</a> from Mozilla Developer Network</li>
<li> <a href="http://dev.opera.com/articles/view/web-workers-rise-up/">"Web Workers rise up!"</a> from Dev.Opera</li>
</ul>
</div>
<div class="row">
<div class="large-6 columns">
<p class="text-left" style="padding:15px 0px;">
<a href="15248846042998.html"
title="Previous Post: Modularizing your GraphQL schema code">« Modularizing your GraphQL schema code</a>
</p>
</div>
<div class="large-6 columns">
<p class="text-right" style="padding:15px 0px;">
<a href="15248829536577.html"
title="Next Post: A tale of Webpack 4 and how to finally configure it in the right way">A tale of Webpack 4 and how to finally configure it in the right way »</a>
</p>
</div>
</div>
<div class="comments-wrap">
<div class="share-comments">
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5ae58078c0d7b2ab"></script>
</div>
</div>
</div><!-- article-wrap -->
</div><!-- large 8 -->
<div class="large-4 medium-4 columns">
<div class="hide-for-small">
<div id="sidebar" class="sidebar">
<div id="site-info" class="site-info">
<div class="site-a-logo"><img src="./asset/img/logo.jpg" /></div>
<h1>Junkman</h1>
<div class="site-des">“拾荒者”一词来自凯文・凯利的《失控》中关于机器学习的故事(“收集癖好机”如何完成他的收集工作)。</div>
<div class="social">
<a target="_blank" class="github" target="_blank" href="https://github.com/panlw/" title="GitHub">GitHub</a>
<a target="_blank" class="rss" href="atom.xml" title="RSS">RSS</a>
</div>
</div>
<div id="site-categories" class="side-item ">
<div class="side-header">
<h2>Categories</h2>
</div>
<div class="side-content">
<p class="cat-list">
<a href="Infra.html"><strong>Infra</strong></a>
<a href="Coding.html"><strong>Coding</strong></a>
<a href="Modeling.html"><strong>Modeling</strong></a>
<a href="Archtecting.html"><strong>Archtecting</strong></a>
</p>
</div>
</div>
<div id="site-categories" class="side-item">
<div class="side-header">
<h2>Recent Posts</h2>
</div>
<div class="side-content">
<ul class="posts-list">
<li class="post">
<a href="15517999043443.html">The Art of Crafting Architectural Diagrams</a>
</li>
<li class="post">
<a href="15517997955971.html">为什么说我们需要软件架构图?</a>
</li>
<li class="post">
<a href="15516128677869.html">DNS Servers That Offer Privacy and Filtering</a>
</li>
<li class="post">
<a href="15516123108194.html">Airbnb's Migration from Monolith to Services</a>
</li>
<li class="post">
<a href="15516097487470.html">Events As First-Class Citizens</a>
</li>
</ul>
</div>
</div>
</div><!-- sidebar -->
</div><!-- hide for small -->
</div><!-- large 4 -->
</div><!-- row -->
<div class="page-bottom clearfix">
<div class="row">
<p class="copyright">Copyright © 2015
Powered by <a target="_blank" href="http://www.mweb.im">MWeb</a>,
Theme used <a target="_blank" href="http://github.com">GitHub CSS</a>.</p>
</div>
</div>
</section>
</div>
</div>
<script src="asset/js/foundation.min.js"></script>
<script>
$(document).foundation();
function fixSidebarHeight(){
var w1 = $('.markdown-body').height();
var w2 = $('#sidebar').height();
if (w1 > w2) { $('#sidebar').height(w1); };
}
$(function(){
fixSidebarHeight();
})
$(window).load(function(){
fixSidebarHeight();
});
</script>
<script src="asset/chart/all-min.js"></script><script type="text/javascript">$(function(){ var mwebii=0; var mwebChartEleId = 'mweb-chart-ele-'; $('pre>code').each(function(){ mwebii++; var eleiid = mwebChartEleId+mwebii; if($(this).hasClass('language-sequence')){ var ele = $(this).addClass('nohighlight').parent(); $('<div id="'+eleiid+'"></div>').insertAfter(ele); ele.hide(); var diagram = Diagram.parse($(this).text()); diagram.drawSVG(eleiid,{theme: 'simple'}); }else if($(this).hasClass('language-flow')){ var ele = $(this).addClass('nohighlight').parent(); $('<div id="'+eleiid+'"></div>').insertAfter(ele); ele.hide(); var diagram = flowchart.parse($(this).text()); diagram.drawSVG(eleiid); } });});</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script><script type="text/x-mathjax-config">MathJax.Hub.Config({TeX: { equationNumbers: { autoNumber: "AMS" } }});</script>
</body>
</html>