【问题标题】:Vue.js inject styles in <body> instead of <head> of index.html (webpack, HtmlWebpackPlugin)Vue.js 在 <body> 而不是 index.html 的 <head> 中注入样式(webpack、HtmlWebpackPlugin)
【发布时间】:2019-10-07 04:50:17
【问题描述】:

基本上,我想实现这个index.html 结构:

<html>
<head>
    <!-- titles, metas and other "static" stuff -->
    <link rel="preload/prefetch" ...> <!-- injected by webpack (ok) -->
    <!-- By default compiled styles are injected here, in head, I want them in body -->

</head>
<body>
<div>
    My static loading animation
    All possible styling is inlined
    It doesn't depend on anything!
    It also could be anything, even just a plain "Loading..." text.
    You still WON'T see it until all style's in head are loaded.
</div>

<div id="app">Vue application goes here</div>

<link rel="stylesheet" href="..."> <!-- Styles injected by webpack (WANTED!) -->
<script src="..."></script> <!-- Scripts injected by webpack (by default, OK) -->

</body>

我想要这个的原因是,我的 html 完全能够向用户显示初始加载动画,并且我希望它index.html 加载后立即呈现,而不是依赖于任何其他资源。 真的,我想这是每个人都想要的,只是说......

但是 debault 的 Vue 配置为将其编译的 styles 包含到 &lt;head&gt; 标记中,这会阻止页面呈现,直到这些样式被加载。我找不到任何关于如何更改它的文档。


更新:图片!

所以,我设法手动模拟了两个变体:

  1. 样式注入&lt;head&gt;(默认)
  2. 样式注入&lt;body&gt;(需要)

以下是视觉差异的图片:

1) 样式注入&lt;head&gt;(默认):

2) 样式注入&lt;body&gt;(需要):

图片上的标签“html 渲染开始”意味着用户实际上看到加载动画,完全在 html 中定义(在我的例子中,一小块 svg 和样式,一般情况下可以是任何东西)并且不依赖于任何其他外部资源来呈现。

【问题讨论】:

标签: vue.js webpack html-webpack-plugin html-rendering loading-animation


【解决方案1】:

解决方案

vue.config.js

class InjectStylesInBody {
    apply(compiler) {
        compiler.hooks.compilation.tap('inject-styles-in-body', (compilation) => {
            if (!compilation.hooks.htmlWebpackPluginAlterAssetTags) return;
            compilation.hooks.htmlWebpackPluginAlterAssetTags.tap('inject-styles-in-body', function(pluginArgs) {
                const { head, body } = pluginArgs;
                head
                    .filter(asset => asset.tagName === 'link' && asset.attributes && asset.attributes.rel === 'stylesheet')
                    .forEach(asset => {
                        head.splice(head.indexOf(asset), 1);
                        body.push(asset);
                    });
            });
        });
    }
}

module.exports = {
    // ...
    chainWebpack: config => {
        // ...
        config
            .plugin('inject-styles-in-body')
            .use(InjectStylesInBody)
        ;
        // ...
    }
    // ...
};

注意事项

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 2017-06-02
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2019-01-31
    • 2016-02-29
    • 1970-01-01
    • 2017-02-21
    相关资源
    最近更新 更多