【问题标题】:How to put script tag before style tag using html webpack plugin如何使用html webpack插件将脚本标签放在样式标签之前
【发布时间】:2017-12-21 04:39:37
【问题描述】:

TL;DR 检查最后一段

我的场景: 我有以下文件:

  • app.css(在 html 中添加到 </head> 之前)
  • vendor.js(在 html 中添加到 </body> 之前)
  • app.js(在 html 中添加到 vendor.js 之后的 </body> 之前)

Html webpack plugin 在我的 html 模板中添加上述文件。 在这种情况下,首先我的浏览器将无法请求下载vendorapp,必须等待样式表首先被下载。那很糟。 第二,当我的 DOM 已经是 SSR 渲染的 html 时,我的脚本将不必要地停止我的 DOM 渲染第一次绘制。

对于第二,我添加了defer 来解决它。但是对于首先,为什么我的defer 脚本必须等待样式表被下载,即使是那些在 DOM 构建中不需要(但只是功能)的脚本!

所以,我想将那些 deferred scripts 放在 head 标签内,这可能与 html webpack plugin可以并行请求这些脚本而不是等待。

首先,您认为这是个好主意吗? (可能是因为浏览器只能有有限的并行连接,所以它可能会阻碍下载图像等。或者可能是现代浏览器在尝试在 html 中向前看并请求延迟脚本时自动执行此操作,但它只是最近的浏览器,不是吗?)

其次,如何使用html webpack plugin实现将延迟脚本放在样式标签之前? (我想具体了解一下)

【问题讨论】:

    标签: javascript html webpack html-webpack-plugin deferred-loading


    【解决方案1】:

    configuration 中设置inject: false 选项以禁用html webpack 插件注入脚本标签,然后将脚本和样式标签自己放置在您的custom template 中:

    webpack.config.js

    plugins: [new HtmlWebpackPlugin({
      template: 'src/index.html',
      inject: false
    })]
    

    index.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
      </head>
      <body>
    
        <%= htmlWebpackPlugin.files.chunks.main.entry %>
      </body>
    </html>
    

    【讨论】:

    • 这是一个很好的建议,但你错过了脚本标签。它应该类似于
    【解决方案2】:

    html-webpack-plugin 有一个配置 inject 有 4 个不同的值:

    new HtmlWebpackPlugin({
       template: './index.hbs',
       inject: 'body'
    })
    

    以及它的作用:

    Option Details
    true will add it to the head/body depending on the scriptLoading option
    false will disable automatic injections
    'body' all javascript resources will be placed at the bottom of the body element
    'head' will place the scripts in the head element

    在此处参考更多详细信息:https://github.com/jantimon/html-webpack-plugin#options

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-10
      • 2016-02-19
      • 2011-08-06
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2011-04-21
      • 2017-06-07
      相关资源
      最近更新 更多