MST
星途 面试题库

面试题:SvelteKit动态路由中如何处理元数据以优化SEO

对于SvelteKit应用中的动态路由,如产品详情页/product/:id 。为了优化SEO,需要为每个动态页面设置合适的元数据(如标题、描述等)。请描述如何在SvelteKit中获取并设置这些元数据,并且确保在服务器端渲染(SSR)时也能正确生效,同时考虑如何避免SEO元数据重复的问题。
48.0万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试
  1. 获取动态路由参数
    • 在SvelteKit中,对于像/product/:id这样的动态路由,你可以在页面组件的load函数中获取参数。例如,在src/routes/product/[id].svelte文件中:
    export async function load({ params }) {
        const productId = params.id;
        // 这里可以根据productId从数据库或API获取产品数据
        return {
            productId
        };
    }
    
  2. 设置元数据
    • 在组件内设置:在Svelte组件中,可以使用document.title来设置页面标题,对于其他元数据(如meta标签中的描述),可以使用document.head来操作。例如:
    <script>
        import { onMount } from'svelte';
        export let data;
        onMount(() => {
            document.title = '产品详情 -'+ data.productId;
            const metaDescription = document.createElement('meta');
            metaDescription.name = 'description';
            metaDescription.content = '这是产品'+ data.productId + '的详细描述';
            document.head.appendChild(metaDescription);
        });
    </script>
    
    • 使用setMeta辅助函数(推荐,利于SSR):SvelteKit提供了一种更好的方式来设置元数据,特别是在SSR场景下。可以创建一个setMeta函数,在load函数中调用。例如:
    import { setMeta } from '$lib/setMeta.js';
    export async function load({ params }) {
        const productId = params.id;
        // 假设从API获取产品数据
        const product = await fetchProductById(productId);
        setMeta({
            title: '产品详情 -'+ productId,
            description: product.description
        });
        return {
            product
        };
    }
    
    • 这里的setMeta函数可以这样实现(src/lib/setMeta.js):
    export function setMeta({ title, description }) {
        if (typeof document!== 'undefined') {
            document.title = title;
            const metaDescription = document.querySelector('meta[name="description"]') || document.createElement('meta');
            metaDescription.name = 'description';
            metaDescription.content = description;
            if (!document.querySelector('meta[name="description"]')) {
                document.head.appendChild(metaDescription);
            }
        }
        return {
            title,
            description
        };
    }
    
  3. 避免SEO元数据重复
    • 唯一标识:确保为每个动态页面生成的元数据是唯一的。例如,在产品详情页中,使用产品的唯一ID来生成标题和描述,避免不同产品使用相同的SEO元数据。
    • 检查与更新:在设置元数据前,先检查是否已经存在相应的元数据标签。如上述setMeta函数中,在创建meta标签前先检查是否已经存在同名的meta标签,如果存在则更新其内容,而不是重复创建。