UNPKG

1.94 kBJavaScriptView Raw
1/*!
2{
3 "name": "Transferables Objects",
4 "property": "transferables",
5 "tags": ["performance", "workers"],
6 "builderAliases": ["transferables"],
7 "notes": [{
8 "name": "Transferable Objects: Lightning Fast!",
9 "href": "https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast"
10 }],
11 "async": true
12}
13!*/
14/* DOC
15Detects whether web workers can use `transferables` objects.
16*/
17define(['Modernizr', 'addTest', 'test/blob', 'test/url/bloburls', 'test/workers/webworkers', 'test/typed-arrays'], function(Modernizr, addTest) {
18 Modernizr.addAsyncTest(function() {
19 var prerequisites = !!(Modernizr.blobconstructor &&
20 Modernizr.bloburls &&
21 Modernizr.webworkers &&
22 Modernizr.typedarrays);
23
24 // Early exit
25 if (!prerequisites) {
26 return addTest('transferables', false);
27 }
28
29 // Proper test if prerequisites are met
30 try {
31 var buffer,
32 scriptText = 'var hello = "world"',
33 blob = new Blob([scriptText], {type: 'text/javascript'}),
34 url = URL.createObjectURL(blob),
35 worker = new Worker(url),
36 timeout;
37
38 // Just in case...
39 worker.onerror = fail;
40 timeout = setTimeout(fail, 200);
41
42 // Building an minimal array buffer to send to the worker
43 buffer = new ArrayBuffer(1);
44
45 // Sending the buffer to the worker
46 worker.postMessage(buffer, [buffer]);
47
48 // If length of buffer is now 0, transferables are working
49 addTest('transferables', buffer.byteLength === 0);
50 cleanup();
51 } catch (e) {
52 fail();
53 }
54
55 function fail() {
56 addTest('transferables', false);
57 cleanup();
58 }
59
60 function cleanup() {
61 if (url) {
62 URL.revokeObjectURL(url);
63 }
64 if (worker) {
65 worker.terminate();
66 }
67 if (timeout) {
68 clearTimeout(timeout);
69 }
70 }
71 });
72});