webwork 多线程技术在服务端技术中已经发展的很成熟了,而在Web端的应用中却一直是鸡肋 在新的标准中,提供的新的WebWork API,让前端的异步工作变得异常简单。 使用:创建一个Worker对象,指向一个js文件,然后通过Worker对象往js文件发送消息,js文件内部的处理逻辑,处理完毕后,再发送消息回到当前页面,纯异步方式,不影响当前主页面渲染。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <!DOCTYPE html> <html > <head > <meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" /> <title > </title > <script type ="text/javascript" > var work = new Worker("work.js" ); work.postMessage("100" ); work.onmessage = function (event) { alert(event.data); }; </script > </head > <body > </body > </html >
work.js
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 onmessage = function (event ) { var num = event.data; var result = 0 ; for (var i = 1 ; i <= num; i++) { result += i; } postMessage(result); } addEventListener("message" , function (event ) { let postData = JSON .parse(event.data); fetch(`date.json?a=${postData.a} &b=${postData.b} ` ).then(function (response ) { return response.json(); }).then(function (data ) { console .log(data); postMessage(data); }).catch(function (e ) { console .log("Oops, error" ); }); }, false ); addEventListener("message" , function (event ) { let postData = JSON .parse(event.data); let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function ( ) { console .log(xhr.status) if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 ){ postMessage(xhr.responseText); }else if (xhr.status >=400 ){ console .log("错误信息:" + xhr.status) } } xhr.open('GET' , `date.json?a=${postData.a} &b=${postData.b} ` , true ); xhr.send() }, false );