-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite-plugin-critical-css.cjs
More file actions
31 lines (26 loc) · 937 Bytes
/
vite-plugin-critical-css.cjs
File metadata and controls
31 lines (26 loc) · 937 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Vite Plugin: Critical CSS Inline
* Inlines critical CSS and makes the main CSS non-blocking
*/
function criticalCssPlugin() {
return {
name: 'vite-plugin-critical-css',
enforce: 'post',
transformIndexHtml: {
order: 'post',
handler(html) {
// Replace the stylesheet link with preload + onload pattern
html = html.replace(
/<link rel="stylesheet"([^>]*)href="\/assets\/index-[^"]+\.css"([^>]*)>/g,
(match, before, after) => {
const href = match.match(/href="([^"]*)"/)?.[1];
if (!href) return match;
return `<link rel="preload" as="style"${before}href="${href}"${after} onload="this.onload=null;this.rel='stylesheet'" />\n <noscript><link rel="stylesheet"${before}href="${href}"${after}></noscript>`;
}
);
return html;
}
}
};
}
module.exports = criticalCssPlugin;