Home > Web Front-end > JS Tutorial > Network optimization code sharing for webpack projects

Network optimization code sharing for webpack projects

小云云
Release: 2018-02-22 13:32:05
Original
1571 people have browsed it

The process of SPA application is:

  1. Load HTML

  2. Load javascript (bundle.js)

  3. Execute javascript and start requesting the interface

  4. First establish an HTTP/HTTPS connection with the interface (dns query/tcp handshake/TLS link)

  5. Send the request header and get the response data...

  6. 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.

Use <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(),
  ]
}
Copy after login

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>
Copy after login

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 %>>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template