Knock at school code, may be considered how to implement this function, how do function a bit cool, but when you enter the company, you will find may code the function implementation is on the other hand, your code also need good style, naming conventions, readability, easy maintenance, and performance, etc. So the following article appears (welcome to point out the error, delete)

1 Naming Rules

By convention, ECMAScript identifiers are camel-case identifiers: the names of variables, functions, attributes, or function parameters are small camel-case identifiers: the first letter of the first word is lowercase, followed by the first letter of the other words is uppercase;

eg:textHeightCopy the code

Big hump: Capitalize every word;

eg:TextHeighCopy the code

1.1 variable

Naming method: small hump naming specification: prefix noun

eg: let minCount = 10  let price = 100Copy the code

Note: All global variable words are capitalized

eg:var PRICE = 100Copy the code

1.2 constant

Naming method: all uppercase words

eg: const PRICE = 100Copy the code

1.3 the function

Function names should describe the function’s function and function naming method: small camel name Naming convention: prefix verbs

Eg: function getHeight() {};function setHeight() {};Copy the code

1.4 Classes and constructors

Naming method: Big camel name Naming convention: prefix name

eg: class Person{
    constructor(name){
        this.name = name;
    }
}
var person = new Person('dadan');Copy the code
Eg:function Person(name){
    this.name = name;
}
var  person = new Person('dadan');Copy the code

2 comments

2.1 Single-line comments

Note: Single-line comment // Use: Leave a space between the comment code (literal) code

2.2 Multi-line comments

Note: Multi-line comments start with /* and end with */. Single-line comments are recommended if the start /* and end */ are both on one line. If there are at least three lines of comments, the first behavior is /* and the last behavior is */Copy the code

3 Loose Coupling

3.1 HTML/js

Although HTML and JS naturally need to interact, some methods couple them too tightly together, as follows

<button onClick="doSomething()"> click < / button >Copy the code

The tight coupling of the event handler attribute values as shown above, if js issues occur, you need to determine whether they occur in HTML parts or JS files, thereby affecting maintainability, or create a large number of Dom structures in JS

body.innerHTML = '<div><ul><li></li><li></li></ul></div>';Copy the code

The above code has a problem. Locating this error is difficult because you first need to look at the page source code to find the inserted HTML, but you can’t find it because it is dynamically generated and if you make changes to the data or layout you will also require js changes, so the HTML rendering should be ‘as separate as possible’ from JS.

3.2 css/js

Sometimes CSS coupling to JS is too tight eg: Change style when triggering focus

Element. Style. Color = "red";Copy the code

If the style sheet needs to be changed in the future, both the CSS and JS files may need to be modified, which is not easy for developers to maintain, so there needs to be a clear division between the two layers to loosen the coupling a bit, as shown below

Element. The className = "edit";Copy the code

Wouldn’t it be better to just change an element’s CSS class so that JS can change the style class without directly affecting the element’s style, and any display problems can be traced back to CSS rather than JS

3.3 Apply logic/event handler coupling

  document.addEventListener('keypress'.function (event) {
      if (event.keyCode === 13) {
        var value = (Math.random() + 1) * 5;
        if(value < 7) { console.log(value); }}});Copy the code

The event handler has event handling in addition to the application logic. The problem with this approach is twofold. First, there is no other way to execute the application logic except through the event. That makes debugging difficult. Secondly, if subsequent events need the same logic, you need to copy the code again. So we need a good solution: separate the application logic from the event handler and encapsulate the application logic as a function

functionGetValue (value) {if(value < 7){
        console.log(value);
    }
    document.addEventListener('keypress'.function (event) {
      if(event.keyCode === 13) { var value = (Math.random() + 1) * 5; getValue(value); }});Copy the code

4 Semantic labels

Semantic means that you can see the content at a glance from the name, and HTML tags are easy to understand from the element names and attribute names, so that the code is better maintained. But when it comes to label for us the fledglings from school to company’s rookies can think of is most div tag + span, remember just to let for example, from the use of the label, to naming variables and functions to code between specification, not a master won’t let me have a headache, because when writing code is too casual, really is too casual, Although it’s a little bit arbitrary right now, if I were to write a page and I would just use a div tag, and then I would only have a div1 or div2 id in the tag, obviously that would be extremely difficult to maintain, so if I changed the tag to

<header>,<nav>,<article>,<sections>,<aside>,<footer>Copy the code

If the navigation bar of the page is div, and the sidebar is div, the only difference between div is ID, if the code is a bit more standard program, it may be

<div id="nav"></div> 
<div id="aside"></div>Copy the code

This may be true of casual programmers who don’t pay much attention to code style

<div id="div1"></div> 
<div id="div2"></div>Copy the code

How about, if you maintain this code, after a month you still remember div1, div2, respectively corresponding to what, do you want to hit the wall, ha ha, so this time if you use HTML5 tag will not be much better

</span> </span>Copy the code

Here’s a rundown of these tags and their usage

<header>: Define the document header <header> <h1> wecOME </h1> <p>My name is da Dan </p> </header>Copy the code
<nav>: Navigation to mark links <nav> <a href="home.index">Home</a>
    <a href="personal.index">Personal</a>
  </nav>>Copy the code
<article> specifies independent self-contained content (representing a single container in a document, page, application, or web site). The <sections> tag defines sections in the document. Such as chapter, header, footer, or other parts of the document, typical scenarios for application (chapter of the article, authoring of the paper, TAB page of the tag dialog) comments: <article> <header> <h1> Don't stay up late </h1> <p> <time pubdate datetime="2017/10/9"></time> </p> </header> <p> Contents... </p> <section> <h1> Comment section </h1> <article> <header> <p> Reviewer </p> <p> <time pubdate datetime="2017/10/10"> < time > < / p > < header > < p > comment < / p > < / article > < section > < article >Copy the code

So look at this example and see if it’s a little clearer

<aside> <h4> Learn tools</h4> <p>Copy the code
<footer> Defines the footer of a document or section. The footer usually contains author information, copyright information, terms of use links, contact information, etc. <footer> <p>Copy the code
Figure > <figcaption> </ Figcaption > <img SRC ="girl.jpg" width="350" height="234" />
</figure>Copy the code

5 Performance Optimization

5.1 Reducing DOM operations

Try not to loop over the DOM, but write once after the loop. Eg: You want to dynamically insert multiple LI child nodes in UL

<ul id="ul">
</ul>Copy the code

1. Loop DOM operations

 window.onload = function{var oUl = document.getelementById (){var oUl = document.getelementById ()"ul");
for(var i = 0; i < 5; I++) {var oLi = document.createelement (" li "); oLi.innerText = i; oUl.appendChild(oLi); }}Copy the code

2. Insert it once

window.onload = function{var oUl = document.getelementById (){var oUl = document.getelementById ()"ul");
var aLi = “”;
for(var i = 0; i < 5; I++) {aLi += "<li>"; ALi + = I; ALi + = "< / li >"; } oUl.innerHtml = aLi; }Copy the code

5.2 Use event proxy

Event bubbling -> events can be processed not only on the time target, but also on any ancestor node of the target. In ancestor node binding event, only need to operate DOM once, can find the target node through the event stream, save time traversing child nodes, for a large number of child nodes to bind, efficiency can be imagined.

<ul id="ul">
        <li>111</li>
        <li>222</li>
        <li>333</li>
        <li>444</li>
</ul>Copy the code

Onload = function(){var oUl = document.getelementById (“ul1”); var aLi = oUl.getElementsByTagName(‘li’); for(var i=0; i

window.onload = function{var oUl = document.getelementById (){var oUl = document.getelementById ()"ul"); oUl.onclick =function(ev) {var ev = ev | | window. The event; var target = ev.target || ev.srcElement;if(target.nodeName.toLowerCase() == 'li') {alert (123); Alert (target. InnerHTML); }}}Copy the code

5.3 Document Reference:

Place references to CSS files in the header and js files in the tail. When the browser encounters a JS file in the rendering process, it will suspend the current rendering process and give priority to the JS process, while the document renders top down. If you put JS in the header of the file, it will affect the subsequent DOM rendering. Typically, if you use Alert in a header file, the browser will pop up an Alert dialog box first, stopping subsequent DOM rendering and causing a blank screen. In other cases, JS may change the structure of a DOM document, typically document.write, causing unnecessary redrawing and rearrangement.

5.4 Reduce redrawing and rearrangement

5.4.1 Repaint is when the appearance of an element is changed without changing the layout (e.g. the visibility, outline, background color, etc.).
5.4.2 Reflow refers to the fact that DOM changes affect the geometric properties (width and height) of the element. The browser will recalcate the geometric properties of the element, invalidating the affected part of the rendering tree. The browser will verify the visibility properties of all other nodes in the DOM tree, which is also the reason for the low efficiency of Reflow. For example, change window size, change text size, change content, change browser window, change style property, etc. If Reflow is too frequent, CPU utilization will shoot up

This rearranges in the following cases: initial rendering of the page add/remove visible DOM elements change element position change element size (width, height, inside and outside margins, borders, etc.) Change element content (text, images, etc.) Change window size 2. Changing the style of a node by setting the style property will result in a reflow every time, so it is better to set the style property by class. For animated elements, the position property should be fixed or Absolute. This will not affect the layout of other elements. If the functional requirement cannot set position to fixed or Absolute, the smoothness of speed is weighed. How to reduce rearrangements? Here’s what I did:

Var curLeft=div.offsetLeft; var curTop=div.offsetTop; div.style.left=curLeft+1+'px';
div.style.top=curTop+1+'px';Copy the code

Style set changes can be added to a class where styles are changed with absolute. 4. Use display: None, do not use visibility, and do not change its z-index 5. Whatever you can do with CSS3, you can do with CSS3.

5.5 other:

Merge images (CSS Sprites) Merge CSS and JS files reduce image resolution change image format (PNG) reduce image save quality and so on