Skip to content

Commit 84c151c

Browse files
Merge pull request #14 from ram-you/patch-1
Update custom.ts to add rel="prefetch"
2 parents be42eaf + 3743c1b commit 84c151c

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/custom.ts

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,11 @@ export interface CustomFonts {
6464
* @default true
6565
*/
6666
preload?: boolean
67+
/**
68+
* Using `<link rel="prefetch">`
69+
* @default true
70+
*/
71+
prefetch?: boolean
6772
}
6873

6974
const resolveWeight = (weightOrSrc?: string | number) => {
@@ -122,7 +127,7 @@ const createFontFaceCSS = ({ name, src, local, weight, style, display }: CustomF
122127
}`
123128
}
124129

125-
const createFontFaceLink = (href: string) => {
130+
const createPreloadFontFaceLink = (href: string) => {
126131
return {
127132
tag: 'link',
128133
attrs: {
@@ -135,6 +140,19 @@ const createFontFaceLink = (href: string) => {
135140
}
136141
}
137142

143+
const createPrefetchFontFaceLink = (href: string) => {
144+
return {
145+
tag: 'link',
146+
attrs: {
147+
rel: 'prefetch',
148+
as: 'font',
149+
type: `font/${href.split('.').pop()}`,
150+
href,
151+
crossorigin: true,
152+
},
153+
}
154+
}
155+
138156
export default (options: CustomFonts, config: ResolvedConfig) => {
139157
const tags: HtmlTagDescriptor[] = []
140158
const css: string[] = []
@@ -146,6 +164,7 @@ export default (options: CustomFonts, config: ResolvedConfig) => {
146164
display = 'auto',
147165
// eslint-disable-next-line prefer-const
148166
preload = true,
167+
prefetch = false,
149168
} = options
150169

151170
// --- Cast as array of `CustomFontFamily`.
@@ -185,7 +204,13 @@ export default (options: CustomFonts, config: ResolvedConfig) => {
185204
.map(src => src.replace(config.root, '.'))
186205

187206
// --- Generate `<link>` tags.
188-
if (preload) tags.push(...hrefs.map(createFontFaceLink))
207+
// --- We can not do a prefetch and a preload for the same files.
208+
if(preload && prefetch){
209+
console.warn('vite-plugin-fonts','We can not do a prefetch and a preload for the same files.');
210+
console.warn('vite-plugin-fonts','The prefetch stand for a lower priority for the resource (maybe we will need it in a future page) whereas preload is for the current page, so we can not have both.')
211+
};
212+
if (preload) tags.push(...hrefs.map(createPreloadFontFaceLink))
213+
if (prefetch && !preload) tags.push(...hrefs.map(createPrefetchFontFaceLink))
189214

190215
// --- Generate CSS `@font-face` rules.
191216
for (const face of faces) css.push(createFontFaceCSS(face))

0 commit comments

Comments
 (0)