Reputation: 307
How to load javascript/css files only for a particular route, say /form
?
If I add them in app.html
under <head>
that works, but causes those files to load even when they are not needed.
I tried to include them using svelte:head
under the svelte file of the corresponding route as follows:
<svelte:head>
<link rel="stylesheet" href="external.css" />
<script src="external.js"></script>
</svelte:head>
This causes the js/css file to load as expected, but only if we directly load/refresh the route like localhost:3000/form
. It doesn't work if I navigate from another page to the /form
route. It seems SvelteKit doesn't re-render the <head>
when navigating.
In short, how can I include assets like css/js but only on certain pages in SvelteKit?
Upvotes: 4
Views: 2865
Reputation: 948
I think it is better to write your style and script directly in your route form like this:
<script>
// here you put your script, you can use method onMount if it is necessary
</script>
<form>
<!-- here you put form code -->
</form>
<style>
//here you put your personnal css
</style>
Normally in Svelte, the style is scoped by default which means that if you write your CSS it has its id for this specific route so even if you use the same class that in another route it will not impact that class. Here there is an example in documentation. And here there is a very good article in CSS-Tricks.
Upvotes: 1
Reputation: 184386
I cannot confirm this behavior. svelte:head
dynamically adds and removes items from the <head>
as the component mounts and gets destroyed. This happens regardless of whether a hard reload or navigation happens.
Either the way you check for this is off or maybe this used to be an issue and you are using an outdated version of SvelteKit.
Upvotes: 2