In all the examples we’ve seen so far, the <script>
block contains code that runs when each component instance is initialised. For the vast majority of components, that’s all you’ll ever need.
Very occasionally, you’ll need to run some code outside of an individual component instance. For example: returning to our custom audio player from a previous exercise, you can play all four tracks simultaneously. It would be better if playing one stopped all the others.
We can do that by declaring a <script module>
block. Code contained inside it will run once, when the module first evaluates, rather than when a component is instantiated. Place this at the top of AudioPlayer.svelte
(note that this is a separate script tag):
<script module>
let current;
</script>
It’s now possible for the components to ‘talk’ to each other without any state management:
<audio
src={src}
bind:currentTime={time}
bind:duration
bind:paused
onplay={(e) => {
const audio = e.currentTarget;
if (audio !== current) {
current?.pause();
current = audio;
}
}}
onended={() => {
time = 0;
}}
/>
<script>
import AudioPlayer from './AudioPlayer.svelte';
import { tracks } from './tracks.js';
</script>
<div class="centered">
{#each tracks as track}
<AudioPlayer {...track} />
{/each}
</div>
<style>
.centered {
display: flex;
flex-direction: column;
height: 100%;
justify-content: center;
gap: 0.5em;
max-width: 40em;
margin: 0 auto;
}
</style>