跳至主要內容

SEO

SEO 最重要的方面是創建高品質的內容,這些內容在網路上被廣泛連結。但是,在建置排名良好的網站時,有一些技術上的考量。

開箱即用

SSR

雖然近年來搜尋引擎在索引使用客戶端 JavaScript 渲染的內容方面有所改進,但伺服器端渲染的內容被索引的頻率更高且更可靠。SvelteKit 預設使用 SSR,雖然你可以在 handle 中停用它,但除非你有充分的理由,否則應該保持啟用。

SvelteKit 的渲染是高度可配置的,如果需要,你可以實現動態渲染。一般不建議這樣做,因為 SSR 除了 SEO 之外還有其他好處。

效能

諸如核心網頁指標之類的訊號會影響搜尋引擎排名。由於 Svelte 和 SvelteKit 引入的額外負擔最少,因此更容易建置高效能的網站。你可以使用 Google 的PageSpeed InsightsLighthouse 來測試你網站的效能。閱讀效能頁面以了解更多詳細資訊。

標準化 URL

SvelteKit 會將帶有尾部斜線的路徑名稱重新導向到不帶斜線的路徑名稱(反之亦然,取決於你的設定),因為重複的 URL 對 SEO 不利。

手動設定

<title> 和 <meta>

每個頁面都應該在<svelte:head>內包含寫得良好且唯一的 <title><meta name="description"> 元素。關於如何撰寫描述性標題和描述,以及其他關於使搜尋引擎理解內容的建議,可以在 Google 的 Lighthouse SEO 稽核文件中找到。

一種常見的模式是從頁面的 load 函式返回與 SEO 相關的 data,然後在你的根 layout 中的 <svelte:head> 中使用它(作為 $page.data)。

網站地圖

網站地圖有助於搜尋引擎優先排序你網站中的頁面,特別是當你擁有大量內容時。你可以使用端點動態建立網站地圖

src/routes/sitemap.xml/+server
export async function function GET(): Promise<Response>GET() {
	return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response

This Fetch API interface represents the response to a request.

MDN Reference

Response
(
` <?xml version="1.0" encoding="UTF-8" ?> <urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="https://www.w3.org/1999/xhtml" xmlns:mobile="https://www.google.com/schemas/sitemap-mobile/1.0" xmlns:news="https://www.google.com/schemas/sitemap-news/0.9" xmlns:image="https://www.google.com/schemas/sitemap-image/1.1" xmlns:video="https://www.google.com/schemas/sitemap-video/1.1" > <!-- <url> elements go here --> </urlset>`.String.trim(): string

Removes the leading and trailing white space and line terminator characters from a string.

trim
(),
{ ResponseInit.headers?: HeadersInit | undefinedheaders: { 'Content-Type': 'application/xml' } } ); }

AMP

現代網頁開發的一個不幸現實是,有時需要建立你網站的加速行動網頁(AMP)版本。在 SvelteKit 中,可以透過設定 inlineStyleThreshold 選項來完成此操作...

svelte.config
/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        inlineStyleThreshold: number;
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    inlineStyleThreshold: number;
}
kit
: {
// since <link rel="stylesheet"> isn't // allowed, inline all styles inlineStyleThreshold: numberinlineStyleThreshold: var Infinity: numberInfinity } }; export default
const config: {
    kit: {
        inlineStyleThreshold: number;
    };
}
@type{import('@sveltejs/kit').Config}
config
;

...在你的根 +layout.js / +layout.server.js 中停用 csr...

src/routes/+layout.server
export const const csr: falsecsr = false;

...將 amp 新增至你的 app.html

<html amp>
...

...並使用從 @sveltejs/amp 導入的 transformtransformPageChunk 轉換 HTML

src/hooks.server
import * as import ampamp from '@sveltejs/amp';

/** @type {import('@sveltejs/kit').Handle} */
export async function 
function handle({ event, resolve }: {
    event: any;
    resolve: any;
}): Promise<any>
@type{import('@sveltejs/kit').Handle}
handle
({ event: anyevent, resolve: anyresolve }) {
let let buffer: stringbuffer = ''; return await resolve: anyresolve(event: anyevent, {
transformPageChunk: ({ html, done }: {
    html: any;
    done: any;
}) => string | undefined
transformPageChunk
: ({ html: anyhtml, done: anydone }) => {
let buffer: stringbuffer += html: anyhtml; if (done: anydone) return import ampamp.function transform(html: string): stringtransform(let buffer: stringbuffer); } }); }
import * as import ampamp from '@sveltejs/amp';
import type { 
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

The handle hook runs every time the SvelteKit server receives a request and determines the response. It receives an event object representing the request and a function called resolve, which renders the route and generates a Response. This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).

Handle
} from '@sveltejs/kit';
export const const handle: Handlehandle:
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

The handle hook runs every time the SvelteKit server receives a request and determines the response. It receives an event object representing the request and a function called resolve, which renders the route and generates a Response. This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).

Handle
= async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve }) => {
let let buffer: stringbuffer = ''; return await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>event, {
ResolveOptions.transformPageChunk?(input: {
    html: string;
    done: boolean;
}): MaybePromise<string | undefined>

Applies custom transforms to HTML. If done is true, it’s the final chunk. Chunks are not guaranteed to be well-formed HTML (they could include an element’s opening tag but not its closing tag, for example) but they will always be split at sensible boundaries such as %sveltekit.head% or layout/page components.

@paraminput the html chunk and the info if this is the last chunk
transformPageChunk
: ({ html: stringhtml, done: booleandone }) => {
let buffer: stringbuffer += html: stringhtml; if (done: booleandone) return import ampamp.function transform(html: string): stringtransform(let buffer: stringbuffer); } }); };

為了防止因將頁面轉換為 amp 而導致任何未使用的 CSS 被發送,我們可以使用 dropcss

src/hooks.server
import * as import ampamp from '@sveltejs/amp';
import module "dropcss"dropcss from 'dropcss';

/** @type {import('@sveltejs/kit').Handle} */
export async function 
function handle(input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}): MaybePromise<...>
@type{import('@sveltejs/kit').Handle}
handle
({ event: RequestEvent<Partial<Record<string, string>>, string | null>event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve }) {
let let buffer: stringbuffer = ''; return await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>event, {
ResolveOptions.transformPageChunk?(input: {
    html: string;
    done: boolean;
}): MaybePromise<string | undefined>

Applies custom transforms to HTML. If done is true, it’s the final chunk. Chunks are not guaranteed to be well-formed HTML (they could include an element’s opening tag but not its closing tag, for example) but they will always be split at sensible boundaries such as %sveltekit.head% or layout/page components.

@paraminput the html chunk and the info if this is the last chunk
transformPageChunk
: ({ html: stringhtml, done: booleandone }) => {
let buffer: stringbuffer += html: stringhtml; if (done: booleandone) { let let css: stringcss = ''; const const markup: stringmarkup = import ampamp .function transform(html: string): stringtransform(let buffer: stringbuffer) .String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)

Replaces text in a string, using a regular expression or search string.

@paramsearchValue A string or regular expression to search for.
@paramreplaceValue A string containing the text to replace. When the {@linkcode searchValue} is a RegExp, all matches are replaced if the g flag is set (or only those matches at the beginning, if the y flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.
replace
('⚡', 'amp') // dropcss can't handle this character
.
String.replace(searchValue: {
    [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
}, replacer: (substring: string, ...args: any[]) => string): string (+3 overloads)

Replaces text in a string, using an object that supports replacement within a string.

@paramsearchValue A object can search for and replace matches within a string.
@paramreplacer A function that returns the replacement text.
replace
(/<style amp-custom([^>]*?)>([^]+?)<\/style>/, (match: stringmatch, attributes: anyattributes, contents: anycontents) => {
let css: stringcss = contents: anycontents; return `<style amp-custom${attributes: anyattributes}></style>`; }); let css: stringcss = module "dropcss"dropcss({ css: stringcss, html: stringhtml: const markup: stringmarkup }).css; return const markup: stringmarkup.String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)

Replaces text in a string, using a regular expression or search string.

@paramsearchValue A string or regular expression to search for.
@paramreplaceValue A string containing the text to replace. When the {@linkcode searchValue} is a RegExp, all matches are replaced if the g flag is set (or only those matches at the beginning, if the y flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.
replace
('</style>', `${let css: stringcss}</style>`);
} } }); }
import * as import ampamp from '@sveltejs/amp';
import module "dropcss"dropcss from 'dropcss';
import type { 
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

The handle hook runs every time the SvelteKit server receives a request and determines the response. It receives an event object representing the request and a function called resolve, which renders the route and generates a Response. This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).

Handle
} from '@sveltejs/kit';
export const const handle: Handlehandle:
type Handle = (input: {
    event: RequestEvent;
    resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}) => MaybePromise<...>

The handle hook runs every time the SvelteKit server receives a request and determines the response. It receives an event object representing the request and a function called resolve, which renders the route and generates a Response. This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).

Handle
= async ({ event: RequestEvent<Partial<Record<string, string>>, string | null>event, resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve }) => {
let let buffer: stringbuffer = ''; return await resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>resolve(event: RequestEvent<Partial<Record<string, string>>, string | null>event, {
ResolveOptions.transformPageChunk?(input: {
    html: string;
    done: boolean;
}): MaybePromise<string | undefined>

Applies custom transforms to HTML. If done is true, it’s the final chunk. Chunks are not guaranteed to be well-formed HTML (they could include an element’s opening tag but not its closing tag, for example) but they will always be split at sensible boundaries such as %sveltekit.head% or layout/page components.

@paraminput the html chunk and the info if this is the last chunk
transformPageChunk
: ({ html: stringhtml, done: booleandone }) => {
let buffer: stringbuffer += html: stringhtml; if (done: booleandone) { let let css: stringcss = ''; const const markup: stringmarkup = import ampamp .function transform(html: string): stringtransform(let buffer: stringbuffer) .String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)

Replaces text in a string, using a regular expression or search string.

@paramsearchValue A string or regular expression to search for.
@paramreplaceValue A string containing the text to replace. When the {@linkcode searchValue} is a RegExp, all matches are replaced if the g flag is set (or only those matches at the beginning, if the y flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.
replace
('⚡', 'amp') // dropcss can't handle this character
.
String.replace(searchValue: {
    [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
}, replacer: (substring: string, ...args: any[]) => string): string (+3 overloads)

Replaces text in a string, using an object that supports replacement within a string.

@paramsearchValue A object can search for and replace matches within a string.
@paramreplacer A function that returns the replacement text.
replace
(/<style amp-custom([^>]*?)>([^]+?)<\/style>/, (match: stringmatch, attributes: anyattributes, contents: anycontents) => {
let css: stringcss = contents: anycontents; return `<style amp-custom${attributes: anyattributes}></style>`; }); let css: stringcss = module "dropcss"dropcss({ css: stringcss, html: stringhtml: const markup: stringmarkup }).css; return const markup: stringmarkup.String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)

Replaces text in a string, using a regular expression or search string.

@paramsearchValue A string or regular expression to search for.
@paramreplaceValue A string containing the text to replace. When the {@linkcode searchValue} is a RegExp, all matches are replaced if the g flag is set (or only those matches at the beginning, if the y flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.
replace
('</style>', `${let css: stringcss}</style>`);
} } }); };

最好使用 handle hook 使用 amphtml-validator 驗證轉換後的 HTML,但只有在你預先渲染頁面時才這樣做,因為它非常慢。

在 GitHub 上編輯此頁面

上一個 下一個