Last active
March 25, 2025 19:09
-
-
Save PierBover/1eb1dc122ce20859fd6c6a2e1c47f598 to your computer and use it in GitHub Desktop.
Keep alive Svelte action
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
import keepAlive from "./action.js"; | |
import Component from './Component.svelte'; | |
</script> | |
<div use:keepAlive={{id: 'some-manual-id', componentClass: Component}}/> |
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
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?