1
votes

How to load javascript/css files only for a particular route, say /form?

I can add them in app.html under <head> and will work, but that will cause these javascript loads for all routes unnecessarily.

I tried to put them using svelt:head under svelte file of the corresponding route as follows:

<svelte:head>
    <link rel="stylesheet" href="external.css" />
    <script src="external.js"></script>
</svelte:head>

This will load make the js/css file to load as expected only if we directly load/refresh the route like localhost:3000/form. But will not work if I navigate from home page to /form route. Seems Sveltekit doesn't re-render the <head> when we naviagate.

Any idea how to do that?

2

2 Answers

0
votes

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.

0
votes

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.