Home > Web Front-end > JS Tutorial > body text

Is it necessary to use server-side rendering to understand javascript?

coldplay.xixi
Release: 2020-11-23 17:54:09
forward
3786 people have browsed it

javascript learning tutorial column introduces whether to use server-side rendering.

Is it necessary to use server-side rendering to understand javascript?

Preface

I recently started a React server-side rendering project. Should I use this? It mainly depends on the scene.

It is more suitable for SEO and first-screen rendering that everyone often talks about. Generally, it is needed for toc business.

isomorphism

There are still many differences between the server-side rendering of modern frameworks and jsp and php. Because nextjs and nuxtjs are not just server-side rendering, they are also isomorphic frameworks.

What is isomorphism? That is, a piece of code can run on both the browser and the server. This is due to the popularity of NodeJS on the server side.

Traditional server-side rendering frameworks such as jsp, php, and django all return html strings, similar to the traditional MPA multi-page mode. Therefore, when switching pages, it will be refreshed and the css and js files will be requested again, resulting in a poor user experience.

The current popular front-end development model is SPA single page, which is based on H5 History to switch pages without refreshing, which can bring a better user experience.

So nextjs and nuxtjs not only support server-side rendering, but also support SPA. Server-side rendering is commonly used for the homepage, and other pages still maintain the non-refresh access mode of SPA.

We have pages written using Django, which is very painful to maintain. Because it is impossible to tell clearly which ones are responsible for the front end and which ones are responsible for the back end. So in order to maintain this, both the front-end and back-end have to learn Python and Django, which greatly increases maintenance costs.

In terms of actual application scenarios, we have several scenarios here that are more suitable for server-side rendering.

Support Post request

One is a reconstructed h5 page. The project was previously written by the Singaporean team using Python Django, so some pages are The third-party website Post submission form opens.

Our reconstructed H5 pages are all hung on Tencent Cloud CDN and cannot be opened with Post. Why not change it to Get? Because this was an agreement they had made before, and the banks are all fathers, so they will not change the agreement for our sake.

The page functions are relatively simple, so in order to catch up with the reconstruction timeline, the friend next to me at the time implemented a version using Express EJS, which only supported ES5 syntax.

Subsequent requirements have changed several times, and it is troublesome to add functions to the original page. For example, if I want to implement JS Bridge, I can only use microbundle to package the existing npm package into a umd file, and then import it using the script tag.

Dynamic Rendering Title

I encountered another requirement a while ago. I need to implement the same H5 page for multiple banks. The functions are basically They are all the same, but the App header needs to display the names of different banks.

In our AirPay App, when the client opens the webview, it will read the title in our HTML and set it as the title of the native header.

If I use document.title in the code, the dynamic setting will not take effect. I can only dynamically set the header through JS Bridge.

But this page will not only be used by AirPay, but also provided by Shopee. It needs to be compatible with two sets of JS Bridge, which is a bit outweighing the gain.

But if you use the server-side direct output method, you can directly determine the title that needs to be rendered on the server side and set it into the HTML title. This is another suitable business scenario.

So based on the previous project, the React server-side rendering function was added to support the development of isomorphic applications with React. Next is not used here, just a set of isomorphisms implemented by myself.

The general implementation idea is to use isomorphic-style-loader and universal-router to handle the isomorphism of styles and routes. After the server obtains the data, it outputs it to window._INITIAL_STATE__. When browsing The processor obtains this initialization data to achieve data isomorphism.

At the same time, the original EJS templates are retained, which are distributed based on Express routing. They can be rendered using EJS or directly exported from the React server.

This page in the first phase is hung on Tencent Cloud CDN. In the second phase, server-side rendering is used. You can obviously feel that the loading speed has become much faster. After all, a loading picture will still be displayed before.

In terms of process guardianship, the entire department’s Node services are performed using the Node Agent written by the boss, and it has withstood the test of various major promotions.

Disadvantages

Of course, server-side rendering should not be abused.

For example, our internal backend management system is powered by Nuxt. Now each local build takes 10 minutes, which greatly affects development efficiency.

Nuxt’s functions are still very powerful, such as dynamically splitting build files based on routing, preloading JS files when the mouse is placed on the Nuxt-link routing component, and so on.

Но реальная выгода практически нулевая, потому что нам не нужно SEO и не нужно улучшать скорость загрузки первого экрана.

Почти все в команде пытались использовать различные средства для оптимизации сборки, но эффект не очень очевиден. Лишь недавно, когда мы начали разделять микро-фронтенды, мы решили эту проблему.

Кроме того, рендеринг на стороне сервера написан иначе, чем рендеринг на стороне клиента, что может легко привести к ошибкам.

Например, следующий код в файле состояния Vuex:

rreee

При открытии страницы время должно отображаться сегодня. Даже если страница расположена по небу, она все равно должна быть в тот же день, когда вы открываете ее и обновляете.

Но в Nuxt отображаемая дата — это дата запуска вашего сервиса. Независимо от того, как вы ее обновляете, она никогда не изменится.

Потому что Nuxt сохранит эти данные в хранилище при инициализации. Независимо от того, как он будет обновлен позже, этот файл не будет перезагружен на сервере, потому что модуль будет кэшироваться Node, поэтому дата будет не обновляться. .

Но при рендеринге на стороне клиента, поскольку обновление страницы приведет к перезагрузке браузером JS-файла, эта дата также будет пересчитана.

Рекомендуется (бесплатно): Урок изучения Javascript

The above is the detailed content of Is it necessary to use server-side rendering to understand javascript?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!