Get Start with Web Worker

2024/3/91 min read
bookmark this
Responsive image

if (window.Worker) {
    const myWorker = new Worker("/js/worker/worker.js");

    var ga = window.ga;

    myWorker.postMessage([ga, document.querySelector("button").textContent]);

    myWorker.onmessage = function(e) {
        console.info('main.js', e);
    }
}
// able to load console at worker thread
console.info('worker');

// can't access document
try {
    var getButtonText = self.document.querySelector("button").textContent;
} catch (error) {
    console.error(error);
}

// can't access main thread's window object
try {
    var x = self.window.ga;
} catch (error) {
    console.error(error);
}

onmessage = function(e) {
    console.info(e);
}
  <script src="js/worker/main.js"></script>

fetch('js/worker.js')
.then(res => res.blob())
.then(blob => {

    var blobUrl = URL.createObjectURL(blob);
    console.log(blobUrl);

    var worker = new Worker(blobUrl);

});
  • https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API#worker_global_contexts_and_functions
  • https://web.dev/learn/performance/web-worker-demo
  • https://web.dev/articles/workers-basics#:~:text=You%20can%20load%20external%20script,with%20the%20importScripts()%20function.
  • https://partytown.builder.io/partytown-scripts