UNPKG

2.13 kBJavaScriptView Raw
1/*!
2{
3 "name": "Workers from Blob URIs",
4 "property": "blobworkers",
5 "tags": ["performance", "workers"],
6 "builderAliases": ["workers_blobworkers"],
7 "notes": [{
8 "name": "W3C Spec",
9 "href": "https://www.w3.org/TR/workers/"
10 }],
11 "knownBugs": ["This test may output garbage to console."],
12 "authors": ["Jussi Kalliokoski"],
13 "async": true
14}
15!*/
16/* DOC
17Detects support for creating Web Workers from Blob URIs.
18*/
19define(['Modernizr', 'addTest'], function(Modernizr, addTest) {
20 Modernizr.addAsyncTest(function() {
21 try {
22 // we're avoiding using Modernizr._domPrefixes as the prefix capitalization on
23 // these guys are notoriously peculiar.
24 var BlobBuilder = window.BlobBuilder;
25 var URL = window.URL;
26 if (Modernizr._config.usePrefix) {
27 BlobBuilder = BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder || window.OBlobBuilder;
28 URL = URL || window.MozURL || window.webkitURL || window.MSURL || window.OURL;
29 }
30 var data = 'Modernizr',
31 blob,
32 bb,
33 worker,
34 url,
35 timeout,
36 scriptText = 'this.onmessage=function(e){postMessage(e.data)}';
37
38 try {
39 blob = new Blob([scriptText], {type: 'text/javascript'});
40 } catch (e) {
41 // we'll fall back to the deprecated BlobBuilder
42 }
43 if (!blob) {
44 bb = new BlobBuilder();
45 bb.append(scriptText);
46 blob = bb.getBlob();
47 }
48
49 url = URL.createObjectURL(blob);
50 worker = new Worker(url);
51
52 worker.onmessage = function(e) {
53 addTest('blobworkers', data === e.data);
54 cleanup();
55 };
56
57 // Just in case...
58 worker.onerror = fail;
59 timeout = setTimeout(fail, 200);
60
61 worker.postMessage(data);
62 } catch (e) {
63 fail();
64 }
65
66 function fail() {
67 addTest('blobworkers', false);
68 cleanup();
69 }
70
71 function cleanup() {
72 if (url) {
73 URL.revokeObjectURL(url);
74 }
75 if (worker) {
76 worker.terminate();
77 }
78 if (timeout) {
79 clearTimeout(timeout);
80 }
81 }
82 });
83});