Skip to content

Instantly share code, notes, and snippets.

Created April 28, 2022 17:11
Show Gist options
  • Save tbranyen/7ade9807a51ff519246480c6e864f5cf to your computer and use it in GitHub Desktop.
Save tbranyen/7ade9807a51ff519246480c6e864f5cf to your computer and use it in GitHub Desktop.
Test page for using workers with diffHTML
<!doctype html>
<html lang="en">
<title>Worker example</title>
<main id="mount"></main>
<script src="http://localhost:8080/packages/diffhtml/dist/diffhtml.min.js"></script>
<script src="./packages/diffhtml-middleware-worker/dist/worker.js"></script>
<script type="module">
const { use, innerHTML } = diff;
const { mainTask, createWorker, toObjectURL } = worker;
// Use a function as a container to write code that will run within the
// Web Worker. This code does not run on the main thread and you cannot
// access globals from it. Useful if you want to avoid writing a second
// file for your worker. The toObjectURL function is a shortcut around
// manually converting the function to a string and generating a blob and
// object URL from it.
const workerURL = toObjectURL(() => {
const { use, html, createTree, innerHTML } = diff;
const { workerTask, getUUID } = worker;
// Make a UUID to represent the thread.
const threadId = getUUID();
// Register the worker middleware.
// Create an empty fragment to render into, this represents the body tag
// in the main thread.
const placeholder = createTree();
let count = 0;
// Simple render function to allow re-rendering.
const render = () => innerHTML(placeholder, html`
<h1>Hello world from a worker thread ${threadId}!</h1>
<button onClick=${ev => {
count = count + 1;
const worker = createWorker(workerURL)(patches => {
// Make sure you pair the patches correct. If you use `innerHTML` in the
// worker, you will also need to do this in the main thread.
innerHTML(mount, null, patches);
use(mainTask({ worker }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment