From the front-end history of server-side rendering

Some time ago in Zhihu saw a question, said is why now popular server-side rendering HTML. Sorted out some online comments, combined with their own ideas, sorted out a front-end development history.

Back in 1989, HTML was created by a physicist to facilitate the sharing of academic documents, and that’s when the front end started. Later, CSS and Javascript joined the front end, which was used to render page styles and handle page dynamic logic. The front-end programmers who started out doing all the basic things like CSS and JS are at the bottom of the programmer’s disdain chain. With the development of the Internet and technological progress, static pages are far from meeting product requirements. Dynamic data should be generated according to logic on the page. At this time, PHP,JSP and other representatives of web1.0 era are ushered in. At this point, the server rendering, “document” as the core idea. Server-side logic treats HTML, CSS, and JS as a static file. There is no distinction between “instructions” and “data” for “documents”; everything is data. So we see server rendering, GET is a request for a file, and one of the most basic components of a lot of server-side frameworks in The Web 1.0 era was document templates, asp, JSP, etc., and the core design idea was to put placeholders in HTML files and then replace them with actual data by server-side logic and then return them. Many small and medium-sized projects, regardless of front-end and back-end, we are all Web development engineers, according to the current parlance called full stack engineers. But now, such a model is there are many problems, take JSP for example, dynamic resources and static resources are completely coupled, the server pressure, and once the situation, the front and back together, the user experience is very poor; JSPS must run in a Java-enabled Web server, and performance is not improved; If the JSP has a lot of content, the page response will be slow… In 1998, IE5.0 introduced XMLHttpRequest technology and realized the function of asynchronous call server. In 2005, Google used Ajax asynchronous communication in its famous interactive applications, and the Web front end led to the 2.0 revolution. Later, the W3C published the XMLHttpRequest standard, which provided the technical foundation for the subsequent Ajax explosion. In 2006, the JQuery library was released and became popular around the world for its simplicity and ability to address browser compatibility. In 2010, Backbone was born and the first RequireJS version was released, and the era of front-end modular development officially came. Then, with the rise of front-end MVC, SPA (Single Page Application) began to become a trend of project development, and the division of labor at the front and back ends was very clear. The front end works on the browser side and the back end works on the server side. Clear division of labor, can make development parallel, test data simulation is not difficult, front-end can be developed locally. At this time, the movement of front and back end separation arose among major companies, and the front end became independent and developed independently. This is an opportunity for the front-end programmers to turn around. However, at this time, a lot of things that should not be made into SPas are made into SPas. However, there are various issues with SPA apps, such as SEO and first-screen loading speed, which make optimization of front-end developers futile. With the rise of Node.js, Javascript becomes capable of running on the server side, which means there’s a new paradigm for development: The Front-end UI Layer handles the presentation logic of the browser layer, while the back-end UI Layer handles routing, templates, data retrieval, cookies, and so on. With Node, the Web Server layer is also JavaScript code, which means that parts of the code can be reused, SEO scenarios can be rendered synchronously on the Server side, and performance issues caused by too many asynchronous requests can be mitigated on the Server side. The deficiencies of the former model are almost perfectly solved by this model. The biggest intellectual revolution of the Web 2.0 era is not the separation of the front and back ends, but the treatment of the Web as a separate application (app). The separation of the front and back ends is simply a corollary of implementing this new architecture. Instruction and data are separate for the program. Instead of getting a rendered web page, HTTP GET gets an HTML and Javascript app that uses the browser as a virtual machine. Loading and displaying data is the running logic after the app starts. What was app traditionally called? It’s called a Client, which is the front end. The browser becomes the running environment of the APP, and the back end degrades into a pure business logic and data interface. Writing Javascript is no longer a gimmick to add special effects to a web page, but a serious project like writing a desktop application. So we see front-end engineering, compilation (translation), various MVC/MVVM frameworks, dependency tools, and so on.

Why server-side rendering?

The main problem with server-side rendering is to solve SEO problems. If the SPA app had good SEO, it wouldn’t have to do server-side rendering. Of course, server-side rendering can solve the first screen loading speed problem is also one of the reasons. So what is SEO? SEO (Search Engine Optimization) : Search Engine Optimization. For example, Google, Baidu need to crawl the website information published by you to carry out natural sorting, is carried out by crawlers. Let’s look at two pieces of code:

Above is the crawler code of two gold-digging articles written long ago (a little low), the general idea is to use superagent to send HTTP request, climb down the whole page (document object), including head, body, etc., and then use Cheerio to parse, and then grab page node elements and key information. And you might think, well, this is easy, because all the information on my page is requested by Ajax and then inserted into the DOM element. Note that the page crawler crawls to doesn’t send an Ajax request, it’s a purely static page initialized, and if you’re using a SPA app, there might be nothing in the body except a node with the ID app. Therefore, we need to have the page rendered on the server and sent to the client as a static HTML document with data information. Of course, there are SEO optimizations for SPA applications that are beyond the scope of this article. Here are some advantages and disadvantages of server rendering:

advantages

  • Good for SEO.
  • The first screen loading speed is fast. Because SPA references need to fetch all the resources on the front screen, server-side rendering just takes the finished product and shows it.
  • No client resources are required. Leaving template parsing to the server consumes less resources on the client, especially on the mobile terminal, and saves power.

disadvantages

  • Occupies server resources. The server completes THE HTML template parsing. If there are too many requests, the server may encounter certain access pressure. If it’s a front-end rendering, you’re spreading the load to the front end.
  • It is not conducive to front and rear end separation.

VUE SSR

Generic (also called isomorphic) JavaScript has become a common term in the JavaScript community. The generic JavaScript term is used to describe JavaScript code that can be executed on the client or server side. VUE’s official documentation describes it this way:

Vue.js is a framework for building client applications. By default, the Vue component can be exported to the browser for DOM generation and DOM manipulation. However, you can also render the same component as HTML strings on the server side, send them directly to the browser, and finally “blend” the static tags into a fully interactive application on the client side.

You can build components and pages using vue.js in a server environment, and then pass the rendered static HTML strings to the client for display. The second half of the sentence is not very smooth, the English version is like this:

“Finally “hydrate” The static markup into a fully interactive app on the client.

After passing the application to the client, the client will have the same interaction (i.e., MVVM bidirectional data binding) due to some static markup.

Vue SSR

Nuxt.js

What is nuxt.js?

Building server-side rendering JavaScript programs is somewhat boring and requires a lot of basic configuration before you can start coding. Thus, nuxt.js was created to solve the vue.js server rendering problem. Nuxt.js is a general application framework based on vue.js. Preset the server side rendering required various configurations, such as asynchronous data, middleware, routing, as long as follow the rules can easily achieve SSR. It’s what Angular Universal is to Angular, next-js is to React. By abstracting the organization of the client/server infrastructure, Nuxt.js focuses on the UI rendering of the application.

What can Nuxt.js do

  • You don’t have to worry about routing, just create.vue files at the corresponding folder level
  • Regardless of the data transfer, NUXT requests data asynchronously before the template output (with the introduction of the AXIos library) and further encapsulates VUex
  • Webpack is built in, eliminating the need to configure webpack, and NuxT packages corresponding files according to the configuration

Nuxt.js installation and running

The command to quickly generate a nuxt project in the case of vue-CLI installation is as follows:

$ vue init nuxt-community/starter-template <project-name>
Copy the code

After entering the project directory

$ npm install
Copy the code

And then start the project

$ npm run dev
Copy the code

In this way, the project can run normally at http://localhost:3000

A practical introduction to nuxt.js

The nuxt.js API can be used at zh.nuxtjs.org/guide. I made a simple demo of nuxt.js myself (extremely simple),Github address, here is some of my own experience, compared to spa applications, to talk about the framework.

1. Nuxt.js directory structure

Nuxt templates are created using vue-CLI, and they have one very important advantage over regular VUE templates: convenience. Nuxt.js has also taken care of the WebPack configuration for our various projects, right out of the box, requiring little change. And even if you need to customize some configurations, they can be easily modified. Let’s compare its directory structure to that of a SPA application.

  • Layouts are used to place a page layout.
  • Middleware is used to house middleware that can be referenced in page components and executed before page logic is executed.
  • Pages simply places all of our page components, but, unlike the SPA app, pages in Nuxt generates routes based on the file and folder structure. For example, the directory structure under my Page folder is as follows
pages/
--| _slug/
-----| comments.vue
-----| index.vue
--| users/
-----| _id.vue
--| index.vue
Copy the code

Nuxt.js generates the corresponding route configuration table as follows:

router: {
  routes: [
    {
      name: 'index',
      path: '/',
      component: 'pages/index.vue'
    },
    {
      name: 'users-id',
      path: '/users/:id? ',
      component: 'pages/users/_id.vue'
    },
    {
      name: 'slug',
      path: '/:slug',
      component: 'pages/_slug/index.vue'
    },
    {
      name: 'slug-comments',
      path: '/:slug/comments',
      component: 'pages/_slug/comments.vue'}}]Copy the code
  • Plugins centrally place plug-ins, such as AXIos, and so on.
  • Store is a centrally defined state tree. Nuxt.js already integrates with Vuex, so you only need to define one hereindex.js“, and then expose an instance of vuex.store. However, after the stomp hole, the state tree here is a little different from the state tree in SPA, but I’ll talk about that later.

2. Nuxt.js page component


  1. State management is the first step in the entire execution process within NUXTactionsThe nuxtServerInit function in, which we’ll talk about later.
  2. And then it goes throughmiddlewareAt this time, data acquisition and page rendering have not been carried out, so we can perform some pre-routing logic in the middleware function, such as user permission judgment.
  3. We can directly call the server interface. For example, axios sends an HTTP request to get the raw data required by the page, and then returns it in the form of an object. At this point, the Vue object has not been instantiated. So asyncData can’t be calledthis.
  4. Fetch is mainly used to fill state tree data.
  5. Once that’s all done, instantiate the Vue object, where the logic is the same as for the single-page application, and nuxt.js will return the application to the front end after assembling the entire page application. Note that you are not returning a page, but an application. Some of the properties of the page local SPA application at this time, such as data listening bidirectional binding.
  6. When the page comes to the front, the mount logic is executed.

    In addition to the application execution process, look at the page rendering module.


  • headPart can customize the current page header information, such as title, meta and so on. Of course, if you need to define a global head, you can do so innuxt.config.jsIn the configuration.
  • layoutSection can be customized page layout, many pages common static header and tail section can be defined on demand reference.
  • scrollToTopUsed to scroll the page to the top when jumping to the page.
  • transitionTransition animation for jumping between pages.

3. Vuex status tree

The whole demo down, so far let me most impressed is the state tree, it and SPA application is still a certain difference. What I needed to complete at that time was to save the user information and use it on any page. If the user information was not obtained from the non-login page, I could jump back to the login page. At first, my design idea was to call the background interface to obtain all information of the user after the user login successfully and store it in store. The flow chart is as follows:






nuxtServerInit
req
req.session.user

actions: {
  nuxtServerInit ({ commit }, { req }) {
    if (req.session.user) {
      commit('user', req.session.user)
    }
  }
}
Copy the code

In combination with the Middleware, user information acquisition and session control can be completed as follows:

4. Other aspects of nuxt.js

Some of the other content involved, in fact, look at the official website tutorial, look at the official website examples can be done, the tutorial is very easy to understand.

conclusion

Using Vue, React and other servers for rendering is not a step down the path of the old template-based rendering. It has moved past history to better things. Nuxt.js, however, is still a very young framework (currently only 0.10.7 on the official website) and still has a lot of problems to improve, but its emergence provides great convenience for vue.js developers to build server-side rendering projects. We’ve heard that Nuxt.js 2.0 is coming, and we’re looking forward to seeing more useful new features in the release.