Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Created April 28, 2022 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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">
<head>
<title>Worker example</title>
</head>
<body>
<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(() => {
importScripts('http://localhost:8080/packages/diffhtml/dist/diffhtml.min.js');
importScripts('http://localhost:8080/packages/diffhtml-middleware-worker/dist/worker.js');
const { use, html, createTree, innerHTML } = diff;
const { workerTask, getUUID } = worker;
// Make a UUID to represent the thread.
const threadId = getUUID();
// Register the worker middleware.
use(workerTask());
// 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>
<h2>Increment</h2>
<button onClick=${ev => {
count = count + 1;
render();
}}>+</button>
<button>-</button>
<b>${String(count)}</b>
`);
render();
});
{
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 }));
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment