Web Worker 就是运行在后台的 js,可以通过 postMessage 返回结果。所有的 Worker 必须与创建者同源。

    Worker - Web API 接口参考 | MDN (mozilla.org)
    mdn/simple-web-worker: A simple web worker test. (github.com)
    Web Workers basic example (mdn.github.io)

    1. // main.js
    2. const first = document.querySelector('#number1');
    3. const second = document.querySelector('#number2');
    4. const result = document.querySelector('.result');
    5. if (window.Worker) {
    6. const myWorker = new Worker("worker.js");
    7. first.onchange = function() {
    8. myWorker.postMessage([first.value, second.value]);
    9. console.log('Message posted to worker');
    10. }
    11. second.onchange = function() {
    12. myWorker.postMessage([first.value, second.value]);
    13. console.log('Message posted to worker');
    14. }
    15. myWorker.onmessage = function(e) {
    16. result.textContent = e.data;
    17. console.log('Message received from worker');
    18. }
    19. } else {
    20. console.log('Your browser doesn\'t support web workers.');
    21. }
    1. // work.js
    2. onmessage = function(e) {
    3. console.log('Worker: Message received from main script');
    4. const result = e.data[0] * e.data[1];
    5. if (isNaN(result)) {
    6. postMessage('Please write two numbers');
    7. } else {
    8. const workerResult = 'Result: ' + result;
    9. console.log('Worker: Posting message back to main script');
    10. postMessage(workerResult);
    11. }
    12. }