Skip to content
OSMD
Language: English
Sponsor
All guides

Docs · OSMD 3.0

OSMD in Svelte

Svelte 5’s $effect fits OSMD well: create it for the element, load and render, and return a function that destroys it.

ScoreView.svelteOSMD 3.0
<script>
  import { OpenSheetMusicDisplay } from 'opensheetmusicdisplay';

  let { url } = $props();
  let container;

  $effect(() => {
    const osmd = new OpenSheetMusicDisplay(container);
    osmd
      .load(url)
      .then(() => osmd.render())
      .catch((error) => {
        // AbortError: url changed, or the component unmounted, before the file arrived
        if (error.name !== 'AbortError') console.error(error);
      });
    return () => osmd.destroy();
  });
</script>

<div bind:this={container}></div>

Use it like any component: <ScoreView url="/scores/my-score.musicxml" />.

The $effect runs once the component is in the page, so container is bound by then. It runs again when url changes, and the function it returns runs before that and when the component is destroyed. Effects don’t run during server-side rendering, so in SvelteKit OSMD only runs in the browser.

What destroy() does

osmd.destroy() is new in OSMD 3.0. It aborts a load() still in flight, releases the loaded score, removes OSMD’s resize observer, takes OSMD’s pages and cursor out of the element and ends the instance. Our CI compiles this component with Svelte’s own compiler, shows a score, switches to a second one and unmounts, then checks that every OSMD instance it made is destroyed and no OSMD element is left on the page.

A url that changes while a file is still loading destroys that instance before the file arrives: its load() is rejected with an AbortError, which the catch lets pass.

Resizing

With autoResize on (the default), OSMD 3.0 watches the element’s width with a ResizeObserver and lays the score out again 200 ms after the width stopped changing. Height changes, like a phone’s address bar sliding in and out, don’t redraw the score. A render() while the element is hidden (a tab that isn’t shown, display: none) is skipped, and the score is drawn once the element has a width.

On OSMD 2.3.1

Before 3.0 there is no destroy(). On 2.3.1, dispose() comes closest: it removes OSMD’s listeners, but leaves the drawing in the element.

Next: The cursor