-
Notifications
You must be signed in to change notification settings - Fork 2
/
inline-worker.html
69 lines (63 loc) · 2.23 KB
/
inline-worker.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Web Worker: Inline worker example</title>
<meta name="author" content="Ido Green">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<style>
#status {
background: lightGreen;
border-radius: 15px;
padding: 15px;
}
article {
background: lightsalmon;
border-radius: 15px;
padding: 15px;
margin-bottom: 15px;
}
</style>
<body>
<h1>Web Worker: Inline worker example</h1>
<article>
This is an example for inline worker that we creating 'on the fly' without the need to fetch
our JavaScript code of the worker from another file.<br/>
It is useful method to create a self-contained page without having to create separate worker file.<br/>
With the new BlobBuilder interface, you can "inline" your worker in the same HTML file as your
main logic by creating a BlobBuilder and appending the worker code as a string.
</article>
<div id="status"></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("<h3>Worker: Started the calculation</h3><ul>");
var n = 1;
search: while (n < 500) {
n += 1;
for (var i = 2; i <= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime!
postMessage("<li>Worker: Found another prime: " + n + "</li>");
}
postMessage("</ul><h3>Worker: Done</h3>");
}
</script>
<script>
function status(msg) {
$("#status").append(msg);
//document.querySelector("#").appendChild(fragment);
}
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)(); //new BlobBuilder();
bb.append(document.querySelector('#worker1').textContent);
// Note: window.webkitURL.createObjectURL() in Chrome 10+.
var worker = new Worker(window.webkitURL.createObjectURL(bb.getBlob()));
worker.onmessage = function(e) {
status(e.data);
}
worker.postMessage(); // Start the worker.
</script>
</body>
</html>