This is the pre-loading implemented on the basis of VUE-CLI4 + VUE 3.0.

ssr

Advantage:

1. Better SEO, conducive to search engines to capture page information.

2. Speed up the first screen rendering

preload

Advantages: can achieve SSR advantages above

Disadvantages: SEO optimization is incomplete

The principle of

The principle of preloading is to run Google Browser during project build and initiate interface request. After obtaining the number of interfaces, render the page and save the rendered DOM page for direct server access.

Install prerender-SPa-plugin (v3.4.0 recommended)

npm i prerender-spa-plugin

Configure in the vue.config file

. const PrerenderSPAPlugin = require("prerender-spa-plugin"); . module.exports = { ... // Preload configureWebpack: config => {if (process.env.node_env! == 'production') return; // Not compatible with router 4.0 return {plugins: [new PrerenderSPAPlugin({// the path of the PrerenderSPAPlugin can be the same as that of the webpakc package. // The path of the PrerenderSPAPlugin can only be one level. StaticDir: path.join(__dirname, "dist"), // routes: [ "/", "/service", "/product", "/about", "/about/newscolum", "/about/enterprise", "/about/message", "/cooperation" ], // Proxy interface configuration Server: {port: 8081, proxy: {"/ API ": {target: "https://www.xxxxxx.com/", changeOrigin: true, secure: true } } }, PostProcess (renderedRoute) {/ / ignore redirects redirects renderedRoute. Route. = renderedRoute originalRoute; return RenderedRoute;}, renderedRoute: new renderer ({inject: {foo: 'bar'}, renderer: new renderer ({inject: {foo: 'bar'}, renderless: False, / / in the main document in js. DispatchEvent (new Event (' render - Event), the name of the Event to corresponding. RenderAfterDocumentEvent: "render-event" }) }), ], }; }}Copy the code

Router. js Route configuration

Vue-router V4.0.0 Route configuration mode createWebHistory mode must be selected

// Vue-router v4.0.0 import {createRouter, createWebHistory, RouteRecordRaw} from "vue-router"; const routes: Array<RouteRecordRaw> = [ { path: "/", name: "/", component: () => import("@/pages/index/index.vue") }, ... ] ; const router = createRouter({ history: createWebHistory(), routes }); export default router;Copy the code

Add renderAfterDocumentEvent to the Mounted life cycle on the page that needs to be preloaded

. mounted() { document.dispatchEvent(new Event("render-event")); },...Copy the code

The result of the NPM run build is as follows: