Angular Universal:提供关键CSS并延迟非关键

Phi*_*hil 5 css lighthouse progressive-web-apps angular-universal angular

这基本上是我正在使用的代码,并且灯塔说我的css包正在延迟我的初始加载。

那么我该如何链接到critical.scss

<head><style>DONT_WANT_TO_WRITE_STUFF_INLINED</style>...</head>

有没有比https://www.npmjs.com/package/critical更好的解决方案,或者内联所有内容?

以及如何延迟主要styles.scss的加载,直到预渲染的Universal内容加载到浏览器中?angular-cli.json中服务器应用程序的配置不包含stylesassets,所以我不明白为什么最初加载styles.scss

RTY*_*TYX 0

关于延迟主要 styles.scss 的加载,我依赖于两件事:

  • 首先,我使用该--extract-css=false标志构建应用程序。这确保了样式包将是一个 JavaScript 文件。
  • 其次,我推迟了该文件的加载。为此,我依赖于一个我调用的小脚本defer.styles.js,该脚本在构建过程结束时运行。该脚本只是查找加载样式的脚本标记,并向defer其添加 a 。
const path = require('path');

const htmlPath = path.join(__dirname, 'dist', 'browser', 'index.html');

fs.readFile(htmlPath, 'utf8', (err, data) => {
    if (err) {
        console.log(err);
        return;
    }

    const index = data.search(`src="styles.`);

    if (index > -1) {
        const output = [data.slice(0, index), 'defer ', data.slice(index)].join('');
        console.log(output);
        fs.writeFile(htmlPath, output, 'utf8', () => {
            console.log('Styles succesfully deferred');
        })
    }
});
Run Code Online (Sandbox Code Playgroud)

关于你的另一个问题 - 如何加载关键的 css -。我仍然没有找到一种舒适的方法。