UNPKG

vite-preload

Version:

Speed up your Vite application by preloading server rendered lazy modules and stylesheets as early as possible

81 lines (78 loc) 2.93 kB
'use strict'; function createHtmlTag({ rel, href, as, type, comment, nonce, asyncScript, }) { let tag = comment ? `<!-- ${comment} -->\n` : ''; const nonceAttr = nonce ? ` nonce="${nonce}"` : ''; switch (rel) { case 'stylesheet': tag += `<link rel="stylesheet" href="/${href}" crossorigin${nonceAttr} />`; break; case 'modulepreload': tag += `<link rel="modulepreload" href="/${href}" crossorigin${nonceAttr} />`; break; case 'module': tag += `<script type="module"${asyncScript ? ' async' : ''} src="/${href}" crossorigin${nonceAttr}></script>`; break; case 'preload': const crossorigin = as === 'font' || as === 'fetch'; tag += `<link rel="preload" href="/${href}" as="${as}" type="${type}"${crossorigin ? ' crossorigin' : ''} />`; break; default: return null; } return `${tag}\n`; } /** * Create a combined Link header separated by , */ function createLinkHeader(modules) { return modules.map(createSingleLinkHeader).filter(Boolean).join(', '); } /** * Creates a single Link header */ function createSingleLinkHeader({ rel, href, as, type }) { switch (rel) { case 'module': case 'modulepreload': return `</${href}>; rel=modulepreload; crossorigin`; case 'stylesheet': return `</${href}>; rel=preload; as=style; crossorigin`; case 'preload': const crossorigin = as === 'font' || as === 'fetch'; return `</${href}>; rel=preload; as=${as}; type=${type}${crossorigin ? '; crossorigin' : ''}`; default: return null; } } function linkPriority(module) { switch (module.rel) { // Stylesheets have the 'Highest' priority in Chrome case 'stylesheet': return 10; // <script> and <link rel=modulepreload> have the 'High' priority case 'module': // Always load blocking scripts before the async script. // This is because if your entry script is async, your polyfill module which is not async will need to be executed first. return module.asyncScript ? 4 : 5; case 'modulepreload': return 2; case 'preload': // Load fonts just below stylesheets. If we don't, there is a higher risk of that the text will flash on the site if (module.as === 'font') { return 9; } return 0; default: return -1; } } function sortPreloads(modules) { return [...modules].sort((a, b) => { return linkPriority(b) - linkPriority(a); }); } exports.createHtmlTag = createHtmlTag; exports.createLinkHeader = createLinkHeader; exports.createSingleLinkHeader = createSingleLinkHeader; exports.sortPreloads = sortPreloads; //# sourceMappingURL=utils.cjs.map