injectFilter()

injectFilter() hook 允许我们控制在 HTML 中注入哪些预加载和静态资源标签以及在何处注入

请参考 指南 > 预加载

Examples

用例

⚠ injectFilter() 是测试版功能:它可能会在任何次要版本更新中发生变化。
⚠ 请注意,injectFilter() 仅在生产中调用:它对开发没有影响。
// /renderer/_default.page.server.ts

import type { InjectFilterEntry } from 'vite-plugin-ssr'

export async function render(pageContext) {
	// ...

	const documentHtml = escapeInject`<!DOCTYPE html>
    <html>
      <body>
        <div id="page-view">${stream}</div>
      </body>
    </html>`

	const injectFilter = (assets: InjectFilterEntry[]): void => {
		assets.forEach((asset) => {
			if (
				// We don't touch entry assets (recommended)
				asset.isEntry ||
				// We don't touch JavaScript preloading (recommended)
				asset.assetType === 'script'
			) {
				return
			}

			// Preload images
			if (asset.assetType === 'image') {
				asset.inject = 'HTML_BEGIN'
			}

			// Don't preload fonts
			if (asset.assetType === 'font') {
				asset.inject = false
			}

			// Preload videos
			if (asset.mediaType?.startsWith('video')) {
				asset.inject = 'HTML_END'
			}
		})
	}

	return { documentHtml, injectFilter }
}
type InjectFilterEntry = {
	inject: false | 'HTML_BEGIN' | 'HTML_END' // Whether and where to inject
	src: string // Asset's URL
	assetType: 'image' | 'script' | 'font' | 'style' | null
	mediaType: string // MIME type
	isEntry: boolean // true  ⇒ <script> or <link rel="stylesheet" type="text/css">
	// false ⇒ preload tag, e.g. <link rel="preload" as="font">
}