trunk icon indicating copy to clipboard operation
trunk copied to clipboard

Shared webworker example

Open krzysiek4321 opened this issue 5 months ago • 4 comments

Added a simple SharedWorker example based on webworker-module example. It demonstrates using both set_on<event> and addEventListener interfaces.

As of this moment this example has a problem to be fixed where the first page which creates a shared worker does not reach the onconnect handler, so it will not receive messages from worker nor be able to post messages to unless it creates a new SharedWorker object which will this time reach already initialized SharedWorkerGlobalScope's onconnect. See worker processing model

You can easily see this by inspecting worker's log in browser's devtools and opening the served example in new tabs. See Using_web_workers#debugging_worker_threads

krzysiek4321 avatar Jul 19 '25 17:07 krzysiek4321

Cool. Could you add this to the CI as well please: https://github.com/trunk-rs/trunk/blob/d8117a85ee277061dc150657b7c22d35cb9c8a6d/.github/workflows/ci.yaml#L167-L184

ctron avatar Jul 21 '25 07:07 ctron

Cool. Could you add this to the CI as well please:

@ctron Done. Do you wish to wait with merging until wasm-bindgen resolves shared worker loading issue?

krzysiek4321 avatar Jul 21 '25 17:07 krzysiek4321

I've found a workaround for the issue. It's to create such a loader shim:

import init from './worker.js';

let initialized = false;

async function initial_handler(e) {
	if (initialized)
		return;

	removeEventListener(self, initial_handler); // all following events will be handled by wasm handler
	await init();
	// necessary because dispatchEvent reaches initial_handler despite removeEventListener
	initialized = true;
	// send the first event into proper handler
	// I've tried to use useTimeout to remove initialized flag, but no good
	self.dispatchEvent(e);
};

self.addEventListener("connect", initial_handler);

Initial handler get's invoked twice, but the initialization block is invoked only once.

@ctron What do you think about this approach?

krzysiek4321 avatar Aug 12 '25 11:08 krzysiek4321

Sorry, I'm not quite following.

ctron avatar Aug 12 '25 13:08 ctron