Home >Web Front-end >JS Tutorial >Network optimization code sharing for webpack projects
The process of SPA application is:
Load HTML
Load javascript (bundle.js)
Execute javascript and start requesting the interface
First establish an HTTP/HTTPS connection with the interface (dns query/tcp handshake/TLS link)
Send the request header and get the response data...
Render the data and present it to the user
We use Vue/React + Webpack The packaged js is often more than 300KB, and step 2 will take a while. If step 2 is in progress, synchronously execute step 4 to establish a connection, you can save a little time.
Especially on the mobile side, establishing a connection takes up a large part of the time, so it can be saved.
<link rel="preconnect">
to let the browser establish the connection in advance. Most mainstream browsers already support: https://caniuse.com/#feat=link-rel-preconnect
Made a simple webpack plug-in: https://github.com /joaner/html-webpack-preconnect-plugin
// $ npm install html-webpack-preconnect-plugin --save-dev var HtmlWebpackPreconnectPlugin = require('html-webpack-preconnect-plugin'); // webpack config { ... plugins: [ new HtmlWebpackPlugin({ filename: 'index.html', // set the preconnect origins preconnect: [ 'http://api1.example.com', 'http://api2.example.com', ] }), // enabled preconnect plugin new HtmlWebpackPreconnectPlugin(), ] }
What this plug-in does is very simple, it is inserted into <head>
:
<!-- dist/index.html --> <head> ... <link rel="preconnect" href="http://api1.example.com"> <link rel="preconnect" href="http://api2.example.com"> </head>
I used the template implementation of HtmlWebpackPlugin
before, but it was a bit cumbersome, so I extracted it into a plug-in.
<!-- template.html --> <link rel="preconnect" href=<%= htmlWebpackPlugin.options.api1_origin %>>
Related recommendations:
Detailed explanation of webpack module and new features of webpack3
Detailed explanation of Webpack server-side code packaging examples
Webpack, vue, node realize single page code sharing
The above is the detailed content of Network optimization code sharing for webpack projects. For more information, please follow other related articles on the PHP Chinese website!