Angular Universal:服务于关键CSS并延迟非关键性

问题描述 投票:5回答:1

这基本上是the code I am using和灯塔说我(几乎是空的!)css捆绑延迟了我的初始负载。

那么如何在中添加一个指向critical.scss的链接

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

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

如何在浏览器中加载预呈现的Universal内容之前延迟主要styles.scss的加载? angular-cli.json中的server-app配置不包含stylesassets,所以我不明白为什么styles.scss最初被加载

css angular progressive-web-apps angular-universal lighthouse
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.