js worker 使用

发布时间 2023-08-22 00:05:13作者: 万物有序

在 IIS 服务器上测试下 Worker,顺便测试字符与 base64 之间的转换。

index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3   <head>
 4     <meta charset="UTF-8" />
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 6     <title>Document</title>
 7   </head>
 8   <body>
 9     <div id="app">
10       <button class="toggle">0</button>
11     </div>
12     <script>
13       const worker = new Worker("/worker.js");
14       const toggle = document.querySelector(".toggle");
15       const chars =
16         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
17       let base64 = "";
18       let binary = "";
19       toggle.addEventListener("click", function () {
20         const text = 1 - this.innerText;
21         this.innerText = text;
22         binary = chars[(Math.random() * chars.length) >> 0];
23         if (text) {
24           worker.postMessage(JSON.stringify({ binary }));
25         } else {
26           worker.postMessage(JSON.stringify({ base64 }));
27         }
28       });
29       worker.onmessage = function (e) {
30         const res = JSON.parse(e.data);
31         if (res.binary) {
32           console.log("%s => %o", base64, res);
33         } else {
34           base64 = res.base64;
35           console.log("%s => %o", binary, res);
36         }
37       };
38     </script>
39   </body>
40 </html>

worker.js

 1 /* 这里只能引入静态 js 文件 */
 2 importScripts("/base64-transform.js");
 3 
 4 self.onmessage = function (e) {
 5   const res = JSON.parse(e.data);
 6   if (res.binary) {
 7     self.postMessage(JSON.stringify({ base64: binaryToBase64(res.binary) }));
 8   } else {
 9     self.postMessage(JSON.stringify({ binary: base64ToBinary(res.base64) }));
10   }
11 };