-
-
Save PierBover/1eb1dc122ce20859fd6c6a2e1c47f598 to your computer and use it in GitHub Desktop.
| 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}}/> |
SvelteKit example:
https://www.sveltelab.dev/ik4iqfuckiv9wvn
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?
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!
This is cool - how do you get it working for page routes?