简体   繁体   中英

How to put script tag before style tag using html webpack plugin

TL;DR Check last paragraph

My Scenario: I'm having following files:

  • app.css (added in html just before </head> )
  • vendor.js (added in html just before </body> )
  • app.js (added in html just before </body> after vendor.js)

Html webpack plugin is adding above files in my html template. In this case, first my browser won't be able to make request to download vendor and app and has to wait for stylesheet to get downloaded first. That's bad. Second , my script will unnecessary stop my DOM to render first paint when it's already SSR rendered html.

For second , I'm adding defer which resolves it. But for first , why my defer script has to wait for stylesheet to get downloaded even those scripts when it's not required in DOM building (but just functionality)!

So, I want to put those deferred scripts inside head tag which is possible with that html webpack plugin but I want to put them before style tag (for external stylesheet) to make benefit that browser can request these scripts parallelly instead of waiting.

Firstly, do you think it's a good idea? (May be because browser can have only limited parallel connections so, it might hinder downloading images, etc. Or may be modern browsers do it automatically as they try to look ahead in html and request defer scripts but it's only recent browsers, isn't it? )

Secondly , how to achieve putting deferred scripts before style tag using the html webpack plugin ? (I want to specifically know this)

Set inject: false option in configuration to disable html webpack plugin to inject scripts tags, then place the script and style tags yourself in your 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>

html-webpack-plugin has a configuration inject with 4 different values:

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

and here what it does:

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

Refer more details here: https://github.com/jantimon/html-webpack-plugin#options

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM