如何将样式异步加载到站点。或者在页脚插入样式?
我使用nuxt:2.0.0
我尝试:
谢谢!
我开发模块:
const STYLE_REGEXP = '<link rel="stylesheet" href="(.+?)">'
const STYLE_TEMPLATE = '<link rel="preload" href="$1" as="style" onload="this.onload=null;this.rel=\'stylesheet\'">' +
'<noscript><link rel="stylesheet" href="$1"></noscript>'
module.exports = async function asyncCss (options) {
this.nuxt.hook('render:route', renderRouteHandle.bind(this))
}
async function renderRouteHandle (url, result) {
result.html = result.html.replace(
new RegExp(STYLE_REGEXP, 'g'), STYLE_TEMPLATE)
}
在 nuxt 3 中,使用此代码可以避免阻塞渲染。将此代码放在 /server/plugins 上
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('render:html', (html) => {
const { head } = html;
const headReplacement = head.map((h) =>
// optimize css load, avoid blocking render
h.replace(
'<link rel="stylesheet"',
`<link rel="preload" as="style" onload="this.rel='stylesheet'"`
)
);
html.head.length = 0;
html.head = headReplacement;
});
});