Open Raphael2b3 opened 5 months ago
an workaround is to load the Custom-Element in a svelte component onMount. +layout.svelte
seems to be a good place.
+layout.svelte
<script>
import { browser } from "$app/environment";
if (browser) {
class CustomElement extends HTMLElement {
connectedCallback() {
this.classList.add("test");
this.innerHTML = `<h1>Hello, Custom element!</h1>`;
}
}
customElements.define("custom-element", CustomElement);
console.log("Custom element is defined");
}
</script>
<custom-element></custom-element>
AND
Now the problem is that custom element is only defined on csr and the website will not be shown if js disabled or until the csr has finished
So we need to include the script at the app.html file.
app.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
<script type="module">
class CustomElement extends HTMLElement {
connectedCallback() {
this.classList.add("test");
this.innerHTML = `
<h1>Hello, Custom element!</h1>
`;
}
}
customElements.define("custom-element", CustomElement);
console.log("Custom element is defined");
</script>
</head>
<body data-sveltekit-preload-data="hover">
<custom-element></custom-element>
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
Its kinda frustrating that its not enaugh to just load the custom-element in app.html but this will do the job aswell
have you tried {@html "<custom-element></custom-element>"}
? It is working for me
This is not an Option for me, since i lose reactivity to state when i want custom-element to depend on state
Describe the bug
When using CustomElements created by js u cant use them in +page.svelte or +layout.svelte file if the pageoption is
ssr = true
andcsr=true
the default.The CustomElement loads first correctly during ssr but after csr has finished it disappears.
How ever when settings ssr=false so that csr=true. It loads correctly.
So customelements work for ssr only and for csr only but not when both is activated.
See the video for demonstration.
https://github.com/sveltejs/kit/assets/70175424/c35204af-ddd8-4b66-b76f-34bbd7649ef0
Reproduction
create the sveltekit project with vite
in the static folder add
custom-element.js
:replace the content of app.html with:
replace the content of
+page.svelte
at the root of your project with:add a file called
+page.ts
:Alternatively unpack this zip archive and run
npm i
andnpm run dev
example.zipLogs
System Info
Severity
annoyance
Additional Information
No response