What is svelte:head in Svelte: Usage and Examples
svelte:head is a special Svelte component that lets you add or update elements inside the HTML document's section from within your Svelte components. It is used to dynamically set things like page titles, meta tags, and links, helping you control the page metadata easily.How It Works
Think of svelte:head as a way to talk directly to the
svelte:head, you can add or change things like the page title or meta tags right where you write your component code.It works by letting you write HTML tags inside the <svelte:head> block, and Svelte will make sure these tags appear in the document's
This is like having a special mailbox inside your component that sends messages to the page's head, so you can keep your metadata close to the component logic that needs it.
Example
This example shows how to set the page title and a meta description using svelte:head. When this component loads, the browser tab will show "Welcome to My Site" and the meta description will be set accordingly.
<script> let pageTitle = "Welcome to My Site"; let description = "This is a simple Svelte app using svelte:head to set metadata."; </script> <svelte:head> <title>{pageTitle}</title> <meta name="description" content={description} /> </svelte:head> <main> <h1>{pageTitle}</h1> <p>Check the browser tab and page source for the head content.</p> </main>
When to Use
Use svelte:head whenever you need to control or update the HTML document's
- Setting dynamic page titles based on the current view or data.
- Adding meta tags for SEO, social sharing, or responsive design.
- Including links to stylesheets, fonts, or icons that depend on the component.
- Updating head content when navigating between pages in single-page applications.
For example, if you build a blog with Svelte, you can use svelte:head to set each post's title and description dynamically, improving SEO and user experience.
Key Points
svelte:headlets you add or update elements inside the HTML from Svelte components.- It supports dynamic content, so head tags can change with your app state.
- Common uses include setting page titles, meta tags, and links.
- It keeps metadata close to the component logic, improving code organization.
Key Takeaways
svelte:head is used to manage the HTML document's section from Svelte components.