Home > Web Front-end > JS Tutorial > Inline Web Workers: When and How to Use Them?

Inline Web Workers: When and How to Use Them?

Mary-Kate Olsen
Release: 2024-10-30 00:14:02
Original
476 people have browsed it

 Inline Web Workers: When and How to Use Them?

Inline Web Workers: A Comprehensive Guide

While web workers are typically defined in separate JavaScript files, there is a method to create them inline within the same HTML file. This approach is advantageous when aiming to minimize the number of separate files for distribution, especially when using tools like the closure compiler for code optimization.

Creating Inline Web Workers

Inline web workers utilize Blob() to create a URL handle to the worker code as a string. This allows the worker to be included directly in the HTML file. Here's a complete example:

HTML with Inline Worker Code:

<code class="html"><!DOCTYPE html>
<script id="worker1" type="javascript/worker">
  // This script won't be parsed by JS engines due to its type.
  self.onmessage = function(e) {
    self.postMessage('msg from worker');
  };
</script></code>
Copy after login

Main JavaScript Code:

<code class="javascript">var blob = new Blob([
  document.querySelector('#worker1').textContent
], { type: "text/javascript" });

// Use window.webkitURL.createObjectURL() for Chrome versions below 11.
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
  console.log("Received: " + e.data);
};
worker.postMessage("hello"); // Start the worker.</code>
Copy after login

In this example, the inline worker code is defined within the

Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template