How should we write high-quality front-end code

Writing high-quality code is one of the essential skills of every programmer, which can effectively carry out project maintenance and project cooperative development

Insert picture description here

01 Preface


This should start from a long time ago. The initial development of the front end is like a cloud of cloud, writing everything together, then scraping together, and finally it can run. In fact, everyone at the front end will have a headache for the confounding of the page. Who does n’t want to optimize it? But why wouldn't there be any molding tools, let alone the high-quality component library now, liberating our code writing from now on, and really doing it out of the box, is it not fragrant?

From the initial development to the present, the code is nothing more than a high degree of decoupling, so that each part is responsible for its own content, and the structure, style and behavior are separated, making the function of the code very clear and comfortable to see anything. So many front-ends later demanded the reconstruction of their own websites. After all, no one wanted to take over the products left over from the next generation. It would be more comfortable for them to rewrite their own set.

02 Difficulties in code maintenance


Why is the front-end code difficult to maintain? In fact, it is mainly due to the following three points:

Browser level

The browser is a tool that our front-end people often interact with. In fact, the browser breeds the front-end family, and it is also the foundation of our survival. If the user doesn't need to see things or interact, or we don't need to exist. I wonder if you have any knowledge of holographic projection? What kind of work are we doing when that technology becomes popular?

Although the compatibility of browsers is getting better and better, mainstream browsers are generally compatible with many css attributes. At least the most commonly used and multi-person ones you must support, such as the fairy attribute of flex layout. When we are accustomed to using a certain browser (such as Google), and then try to use the 360 ​​browser, you will find that you can not see the root. Just like you are used to Google search, but it requires you to use Baidu.

Therefore, compatibility between front-end browsers is a hurdle that we must cross. Even if the compatibility is getting better and better, there are many users who use IE or 360 browsers, and we cannot ignore their use. But there is a saying that compatibility with IE is a waste of life.

technical level

Since each company uses different technologies, in fact many companies will have their own internal frameworks. We have to use their internal frameworks to integrate with existing technical frameworks, which is also a headache. Even if you are an employee who just jumped in, you still have to learn their internal technical framework before you can develop the project.

Many companies may not have the fairy frameworks such as vue and react when they were founded, which is the world of jQuery. The bottom layer of our project cannot be changed overnight, so many companies will not use it even if they know the emergence of new technologies. Is also in the exploration stage. Suppose that the company needs to use a new technology to refactor the code, or because the employees' understanding of the new technology is not deep enough, the written code will also have certain design vulnerabilities. So without a deep understanding, it is easy to write code that is difficult to maintain, causing reading difficulties for our team, and it will eventually become a difficult-to-maintain project.

teamwork

Teamwork is the real problem. Unlike projects that we write ourselves, we can write whatever we want, and we are not afraid that we may not understand it. When we submit the code, we don't need the consent of other members to push directly to the master branch. These are all our personal development practices, to the company level or project level, then you just pick up things.

Large-scale projects generally have more developers. Everyone will be responsible for different modules and different functions. Everyone will have their own independent branch. The code must be reviewed when it is merged into the main branch. This is a perfect 3. System development process. So the more complex the project, the higher the teamwork requirements. Generally, we will have a code development rule, everyone should abide by each other, otherwise we will pollute the normal code, making the project difficult to maintain. The biggest difficulty in teamwork is not technology but people.

summary:

In addition to decoupling the code of our project and separating the structure, style and behavior, we should also pay attention to the characteristics of simplicity, reusability and structure. When you can do this, your project will look professional, the code will be more maintainable and extensible, and it will be easier for developers to add new features or modules.

03 High-quality structure code


Semantic

After HTML5 came out, many new tags and attributes were added, and the concept of semantics appeared in the eyes of front-end people. Before we wrote structural code, we generally chose to use div and class name / ID name to name a module. This is the so-called DIV + CSS development model. So is this approach feasible? Of course it is feasible, and others are very comfortable with it, that is, the cv operation is a little more.

Of course, there are disadvantages. For example, the most important thing is that the structure is not clear. Whether it is to write navigation or modules, or the bottom, the whole div. This structure is not clear. If you don't add the class name or ID name, you don't know which module your code belongs to. And there is another point is that it is not friendly to search engines, can not accurately identify your website structure and information.

So how do you see if your code is semantic? Very simple, remove all styles, to see if your page structure is displayed properly, general semantic tags will have default styles. If the display is okay, the structure is well-ordered and the semantics are better. Otherwise, you can write it again.

Modular

Modularity actually follows semantics. If your semantics are better, then the corresponding modularity is better. I think the focus of modularization should be on whether your label selection is reasonable. For example, the text should use p / span tags, and the title should use H1-6 tags. Not all text is to use div as a universal label element. If you can use p, don't use div, because p itself is for text and has a certain basic style.

summary:

But now we don't seem to pay attention to these things, because with the emergence of high-value component libraries, what needs to be directly used by cv. But what we pay attention to is not that this is the reason for you to avoid learning, because no matter how tall the components are composed of the most basic styles and structures, the idea of ​​making wheels behind the learning is the most important. When the component can not meet the business needs, you need to write css code.

04 High-quality style codes


Box model

In general interviews, you will be asked more or less about your understanding of the css box model. If you are not prepared, your friends may confuse the content. Repeat it again here:

  • IE: The width of the element consists of width + border + padding
  • Standard: The width of the element is width, which includes padding + border
Style organization

How to write the style of our page is also an issue that we have to consider. Our style writing is not good or bad, only good or bad. It is the right style to write down the page to meet your expectations. Whether it is reasonable is another matter.

So here you can refer to the structure of the style: reset.css + common.css + view.css

First, the first is the basic style standards, focusing on the underlying style. Here, reset means that we reset all the default basic styles of the browser, and try to satisfy all browser styles to be consistent. Remember when we said the wildcard * before? It is a very violent style reset, but it is also a very dangerous operator. The danger is that you need to traverse all the element nodes of the page and style him. Here we recommend using the online reset.css, there are many for you to choose, if you are too lazy to find and the project supports npm installation, directly npm i reset-css can be simple, fast and convenient.

common.css refers to some component-related styles. For example, if we write code in vue, we know that a vue file can be composed of three parts, one of which is for you to write style code that belongs to the component. Here we reuse the component Will be very convenient. About view.css is actually a higher-level preparation, belonging to a page style file.

Selector use

The selector can write a style for a certain node. Some students may say that I can apply my node style successfully. Do I still need to care about how to use it? In fact, let ’s start with the matching scheme of the CSS selector. The selector is matched from right to left. A selector such as .class ul li ap will first match the p tag from the global and then the a tag. And so on.

So the first problem is that we must avoid selector nesting too deep, because it is very performance-intensive. If the ID can be matched to the unique element, then no other selector is needed. It is precisely because of this matching rule of the selector that the elements are more efficiently matched, which is also the conclusion after long-term verification. Finally, we should pay more attention to the inheritance of styles and avoid writing repeated styles many times. The so-called less combination and more inheritance principles are used.

The css preprocessor that has appeared in recent years can effectively improve the writing of styles. It uses an object-oriented writing method and reuses style codes to a greater extent. There are stylus, scss, and less.

Coding style

Style style: The coding style of css is also different from person to person. Generally speaking, we should use multi-line writing, because it is more readable. If the style code is written on one line, it will inevitably cause reading difficulties. Later, when we release the project, we can compress the code.

id / class: The id selector is generally used on globally unique element nodes. If it is determined that the element nodes are unique, we can use them, but if the element nodes are not unique, then it is recommended to use class.

05 High-quality behavior code


Good habits

Because the project involves multi-person development, the variables used by each person should be maintained by themselves, which can effectively avoid code conflicts and cover normal code. Therefore, we should prohibit writing code directly in the global scope, which can easily affect other people's project modules. So what are our avoidance methods?

  • Teamwork to avoid conflict

We write our code in an anonymous function, such as (function () {}) (), so that the variables in the code will not be global, but internal variables that belong to this function, not to others The code has an impact. Wrapping the code in an anonymous way can effectively control global variables and avoid potential conflicts.

  • Unified entrance

We can also load a file for the function with a unified entry point, and we can select the function entry point as init, so that all initialization operations will be performed here. Through this we can simulate the DOMReady event.

  • CSS at the head, JS at the bottom

This operation should be a practice that everyone should follow, which is more conducive to the optimization of the loading of browser pages, reducing the time of blank pages and improving the user experience.

JS layering

In fact, the layering here is the same as the layering of CSS. You can also refer to the form of the base layer, common layer, and view layer. The base layer can encapsulate the differences of different browsers, provide a unified interface, and accomplish some compatible tasks. The common layer provides reusable components. Its function is to provide components to the view layer. Both the common layer and the base layer can provide components for the view layer, the difference is that the common layer can provide larger components. For example, the realization of some drag and drop functions. The view layer is a direct call to the first two layers. Here is the implementation of the page logic, such as operations related to specific functional requirements such as interface requests.

Practical tips
  • elasticity

Elasticity means that we can easily respond to the demands put forward by customers without modifying some js code every time a requirement is added, which is very inconvenient. For example, like the event proxy, you can implement some streamlined operations without manually adding event listener functions for each added node.

  • Reusability

Now basically what functions we implement must first consider how to reuse this code to reduce some business-related or functional-related code, so that it can be written once and available everywhere. It is our pursuit to be common and not affect the function between components. We can implement the method by passing parameters.

  • Avoid side effects

The basic code we developed may be able to meet our current needs, but we may also have some side effects during the use process that we do not want. In order to avoid this problem, we should consider whether our function coupling is too high, Consider decoupling, etc.

06 Summary


Today, I will talk to you about writing high-quality code. In fact, there are still many aspects that are too late to write. Readers can also consult relevant information themselves. It is mainly explained from three aspects of structure, style and behavior, which is also the basic language corresponding to our front-end html, css and js.

In terms of structure, we talked about semantic writing and modular writing. In terms of style, we talked about box model, style writing, style style, and use of selectors. In terms of behavior, we talked about good habits of writing, js layering, etc.

In fact, the specific implementation has to be understood by everyone. These are the experiences summarized by the predecessors. The specific details in the project can be written according to the above rules. I believe it should improve a code quality level.

Insert picture description here

Published 57 original articles · won praise 6 · views 6419

Guess you like

Origin blog.csdn.net/weixin_42724176/article/details/105320447
Recommended