Open xyzdata opened 6 years ago
demo OK
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Web Workers</title> </head> <body> <!-- Web Workers --> <script> const css = ` color: #f0f; font-size: 23px; `; const url = `https://cdn.xgqfrms.xyz/json/xgqfrms.json`; /* js 主线程 */ // 创建一个Worker对象并向它传递将在新线程中执行的脚本的URL let worker = new Worker("worker.js"); // 向 worker 发送数据 worker.postMessage(url); // 接收 worker 传过来的数据函数 /* Uncaught DOMException: Failed to construct 'Worker': Script at 'file:///E:/000-xyz/worker.js' cannot be accessed from origin 'null'. // to run this demo, you need to using a web server as an container! */ worker.onmessage = function(e) { console.log(`%c worker 线程 e = \n`, css, e); console.log(`%c worker 线程 data = \n`, css, e.data); // 输出 worker 发送来的数据 } </script> </body> </html>
worker.js
/* worker 线程 */ // another namespace ??? const css const css = ` color: #0ff; font-size: 23px; `; const css_fd = ` color: #0f0; font-size: 23px; `; // callback function onmessage = function (e){ // let id = e.data;//通过evt.data获得发送来的数据 console.log(`%c 主线程 e = `, css, e); // MessageEvent {isTrusted: true, data: "hello world", origin: "", lastEventId: "", source: null, …} // data: "https://cdn.xgqfrms.xyz/json/xgqfrms.json" // console.log(`主线程 id = `, id); // 主线程 id = hello world // fetch data const datas = [];// {} // const url = `https://cdn.xgqfrms.xyz/json/xgqfrms.json`; let url = e.data; // decodeURI() console.log(`%c 主线程 url = \n`, css, `"${url}"`); fetch(url = `https://cdn.xgqfrms.xyz/json/xgqfrms.json`) .then(res => res.json())// SyntaxError: Unexpected token / in JSON at position 0 at fetch.then.res (worker.js:18) .then( (json) => { // console.log(`fetched json = \n`, JSON.stringify(json, null, 4)); let userInfos = json.user; console.log(`%c userInfos = \n`, css_fd, JSON.stringify(userInfos, null, 4)); datas.push(userInfos); postMessage(userInfos); // 将获取的数据发送到主线程 } ) .catch(err => console.log(`fetch error = \n`, err)); // postMessage(datas);// 将获取的数据发送到主线程 } /* ??? 动态加载 js modules */
https://github.com/xgqfrms/ES6/issues/9
???
https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts
https://www.cnblogs.com/xgqfrms/p/11242198.html https://www.cnblogs.com/xgqfrms/p/11242870.html
web worker