npm i --save-dev html-prefetch-css-webpack-plugin
This is a webpack plugin, work with html-webpack-plugin. inject prefetch link to html head;
while use code spilting in webpack, we can use magic comment to mark module that we want to prefetch;
like this
/* webpackPrefetch: true */
but the split css file won't be prefetched;
before load
... ...
after loaded
... ...
although the js file be prefetched, css file still need to wait;
to solve this problem, we can use 'style-loader' to integrate css to js file;
webpack.config.js
moduleexports = ... module: rules: test: /css$/ loaders: 'style-loader''css-loader' ...
else use this plugin
before load
... ...
index.js
const button = document;buttoninnerText = "lazy load btn";button;documentbody;
lazy.js
; const lazy = document; lazyclassList; lazyinnerHTML = content; return lazy;;
lazy.css
webpack.config.js
const HtmlWebpackPlugin = ; const MiniCSSExtractPlugin = ; const PrefetchCssWebpackPlugin = ; moduleexport = entry: "index.js" output: path: __dirname + "/dist" filename: "index.bundle.js" module: rules: test: /\.css$/ use: MiniCSSExtractPluginloader "css-loader" plugins: "[name].css" ;
the generated html file would be
Webpack App