2024-04-17


queueMicrotask()
I had an issue in Svelte 5 where I tried to use .focus() but it only worked in SSR, not when SSR was disabled.
const patternSelector = document.querySelector<HTMLButtonElement>("#nejime button")!;
patternSelector.focus();
Dominic from the Svelte team explained that SvelteKit tries to restore focus and this conflicted with the focus() I was trying to execute. To fix this I could use queueMicrotask() which makes sure my code runs after SvelteKit is done.
const patternSelector = document.querySelector<HTMLButtonElement>("#nejime button")!;
queueMicrotask(() => {
  patternSelector.focus();
});
Thanks Dominic! 😊
Go back to all posts