Skip to content

Instantly share code, notes, and snippets.

@PierBover
Last active March 25, 2025 19:09
Show Gist options
  • Save PierBover/1eb1dc122ce20859fd6c6a2e1c47f598 to your computer and use it in GitHub Desktop.
Save PierBover/1eb1dc122ce20859fd6c6a2e1c47f598 to your computer and use it in GitHub Desktop.
Keep alive Svelte action
const instances = {};
export default function (node, {id, componentClass}) {
if (instances[id]) {
node.appendChild(instances[id]);
} else {
const wrapper = document.createElement('div');
const instance = new componentClass({
target: wrapper
});
instances[id] = wrapper;
node.appendChild(wrapper);
}
}
<script>
import keepAlive from "./action.js";
import Component from './Component.svelte';
</script>
<div use:keepAlive={{id: 'some-manual-id', componentClass: Component}}/>
@kirkbushell
Copy link

This is cool - how do you get it working for page routes?

@khromov
Copy link

khromov commented Mar 18, 2024

@BraveDevelopment
Copy link

OMG thats so good! Searched for this soooo long....

Btw to make the script work in svelte 5 you need to change line 9-12 from :
const instance = new componentClass({ target: wrapper });
to
const instance = mount(componentClass, { target: wrapper, })
and import mount (import { mount } from 'svelte';) at the top.

I still have a question.
I have an iFrame in my component that I cached and the iFrame is loading again every time I mount the component... Could that be fixed somehow?

@fedebram
Copy link

Has anyone tried to implement this action using Svelte 5? I used the new mount function, but unfortunately the reactivity is lost.
Is there a way to store component instances in Svelte 5? It would be great if there were a way to cache components. If anyone has a solution, please share it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment