Skip to main content

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):

AudioPlayer
<script module>
	let current;
</script>

It’s now possible for the components to ‘talk’ to each other without any state management:

AudioPlayer
<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;
	}}
/>

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<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>