Svelte Releases New "Attachments" Feature to Enhance DOM Interactivity and Responsiveness

2025-06-17

The latest version of Svelte introduces a new feature called "attachments," which enhances the performance of DOM by improving the interactivity and responsiveness of web applications. This new attachment feature in Svelte replaces the previous Svelte actions.

Similar to Svelte actions, developers can use attachments to execute code when a component or DOM element is mounted or unmounted. Typically, this code sets up listeners for specific events and removes them when the attachment target is unloaded. Attachments can also be integrated with third-party libraries that require access to the target DOM elements. Attachments dependent on reactive values will re-run whenever those values change.

Here's an example using the ScrambleTextPlugin from the GSAP animation library:

<script>
import { gsap } from 'gsap'
import { ScrambleTextPlugin } from 'gsap/ScrambleTextPlugin'

gsap.registerPlugin(ScrambleTextPlugin)

// ⚠️ Attachments reside inside `$effect`
function scramble(text, options) {
return (element) => {
gsap.to(element, {
duration: 2,
scrambleText: text,
...options
})
}
}

let text = $state('Svelte')
</script>

<!-- Tracking context -->
<input type="text" bind:value={text} />
<div {@attach scramble(text)}></div>

When the DOM is initially mounted, the text 'Svelte' will be scrambled. Moreover, any further changes to the text value will also trigger the scrambling effect. Developers can experiment with this example in the Svelte playground.

Therefore, Svelte's attachment functionality extends Svelte actions, which do not provide similar reactivity for their parameters. Additionally, Svelte attachments can be applied to Svelte components, whereas Svelte actions are limited to declarations on DOM elements. This version offers a mechanism to create attachments from actions, allowing developers to reuse existing action libraries.

Attachments can encapsulate behavior separately from markup (similar to practices in other UI frameworks, like hooks in React). Examples of behaviors previously implemented as actions and now benefiting from the attachment feature include clipboard copy, pasting clipboard content into elements, capturing clicks outside an element, masking user input, animating elements, pointer drag-scroll behavior, providing keyboard shortcuts, making elements swipeable, triggering downloads on click, and more.