SSR and pre-rendering mechanism summary

  Emergence of Ajax technology, so that our Web applications can display different content pages without refreshing the state, which is a single-page application. In a one-page application, often only a html file, and then to match the corresponding routing script based on url to access, dynamically rendered page content. Single-page application to optimize the user experience, but also brought us a lot of problems, such as SEO unfriendly, the first visible screen time is too long. Server-side rendering (SSR) and pre-rendered (Prerender) technology is to solve these problems and students.

First, what is the server-side rendering

  Simple to understand is the component or string generated html page through the server, and then sent to the browser, and finally static marks "hybrid" is fully interactive application on the client.

1, SSR advantage

  (1) more conducive to SEO: different reptile work on similar principles, only crawling source, not any script execution site (except for Google, said to Googlebot can run javaScript). After using React or other MVVM framework, most of the page DOM elements are dynamically generated based on the client js, reptiles crawl for content analysis is greatly reduced. In addition, the browser reptiles will not wait for us to go fetch data after the completion of our page data. Service returned to the client-side rendering is asynchronous data have been acquired and perform a final HTML JavaScript script, the network can climb in to grab a full page of information.

  (2) more conducive to the first screen rendering: rendering the fold is sent from html string node, it does not depend on js files, which will make the users to quickly see the contents of the page. Especially for large single-page application, the package file size is relatively large, rendering ordinary client load all the required documents for a long time, Home will have to wait a very long time black and white.

2, the server rendering and pre-rendered distinguished

  The client rendering: user access url, html file request, the front page rendering dynamic content based routing. The key link is longer, there is a certain time of black and white;

  Side rendering services: user access url, the server requests the required data according to the access path, spliced ​​into html string, it returns to the front end. When the front end part of an existing received html;

  Pre-rendered: Construction of an html file generated phase pre-rendered matching path (Note: Each requires a pre-rendered route has a corresponding html). Html file has been constructed out of parts of

3, server-side rendering and pre-rendered in common

  For single-page application, and server-side rendering pre-rendered together to solve the problem:

  (1) SEO: Web content single page application is based on the current path of dynamic rendering, html files are often not content, the web crawler will not wait until the page script completes re-crawl;

  (2) weak network environment: When a user visits your site in a weak environment, you will want to render the content as soon as possible to them. Even loaded and pre-parsed js script;

  (3) lower version of the browser: the user's browser may not support js the features you use pre-rendered or server-side rendering allows users to at least be able to see the contents of the first screen instead of a blank page.

  Pre-rendered and can render the server as SEO optimization to improve, but the former than the latter requires less configuration, low cost. Weak network environment, pre-rendered page content can be rendered more quickly, reducing the time the page is visible.

4, what is not suitable for use pre-rendered scenes

  Does not apply to too many pre-rendered rendering routing ( not recommended for pre-rendered a lot of routes, because it can seriously slow down your build process ) and dynamic routing (such as / detail / parameter because the page content based on the parameters seem to see it different ), applicable only to a few simple fixed routing scenarios (e.g. / index / about / contact)

  Frequently changing content: If you pre-render a game list, this list will be as new players to record and update your pre-rendered pages will not display correctly until the script is loaded and replaced with the new data, which is a poor user experience;

二、Prerender SPA Plugin

  prerender-spa-plugin webpack is a plug-in for pre-rendered static html content in a single page application. Therefore, the plug defining a single page of your application must use webpack build, and it is a framework for independent, whether you are using React or even Vue does not use frames, can be used for pre-rendered.

1, prerender-spa-plugin principles

  The principle is very simple, is to build the final stage in webpack, start a phantomjs locally, access to the configuration of the pre-rendered route, then phantomjs rendered page output to the html file and establish a route corresponding directory.

  View prerender-spa-plugin source  prerender-spa-plugin / lib / Phantom-Page-render.js .

// Open the page 
page.open (url, function (Status) { 
  ... 
  // not set the hook capture, captured in the script completes 
  IF (
     ! Options.captureAfterDocumentEvent && 
    ! Options.captureAfterElementExists && 
    ! Options.captureAfterTime 
  ) { 
    / / splice HTML 
    var HTML = page.evaluate (function () {
       var DOCTYPE = new new window.XMLSerializer (). serializeToString (document.doctype)
       var the outerHTML = document.documentElement.outerHTML
       return DOCTYPE + the outerHTML 
    }) 
    returnResult (HTML) //Capture Output 
  } 
  ... 
})

2, How to Use

  installation:npm install prerender-spa-plugin --save

  vue.config.js increase

const PrerenderSPAPlugin = require('prerender-spa-plugin');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const path = require('path');
module.exports = {
    configureWebpack: config => {
        if (process.env.NODE_ENV !== 'production') return;
        return {
            plugins: [
                new PrerenderSPAPlugin({
                    // 生成文件的路径,也可以与webpakc打包的一致。
                    // 下面这句话非常重要!!!
                    // 这个目录只能有一级,如果目录层次大于一级,在生成的时候不会有任何错误提示,在预渲染的时候只会卡着不动。
                    staticDir: path.join(__dirname,'dist'),
                    // 对应自己的路由文件,比如a有参数,就需要写成 /a/param1。
                    routes: ['/', '/product','/about'],
                    // 这个很重要,如果没有配置这段,也不会进行预编译
                    renderer: new Renderer({
                        inject: {
                            foo: 'bar'
                        },
                        headless: false,
                        // 在 main.js 中 document.dispatchEvent(new Event('render-event')),两者的事件名称要对应上。
                        renderAfterDocumentEvent: 'render-event'
                    })
                }),
            ],
        };
    }
}

  在main.js增加

new Vue({
  router,
  store,
  render: h => h(App),
  mounted () {
    document.dispatchEvent(new Event('render-event'))
  }
}).$mount('#app')

  router.js 中设置mode: “history”。预渲染的单页应用路由需要使用 History 模式而不是 Hash 模式。原因很简单,Hash 不会带到服务器,路由信息会丢失。

  验证是否配置成功:运行npm run build,看一下生成的 dist 的目录里是不是有每个路由名称对应的文件夹。然后找个 目录里 的 index.html,看文件内容里是否有该文件应该有的内容。有的话,就设置成功了。

Guess you like

Origin www.cnblogs.com/goloving/p/11285773.html