What procedures should pay attention to the white ape

In schools knocking code, consideration may be how to achieve this function, how to do cool little feature, but when you get into a company, you'll probably find the code to achieve the function is on the one hand, you also need the code good coding style, naming, readable and easy to maintain, and performance and so on, so there have been the following article (welcome to point out the error, invasion deleted)

1 naming rules

Conventionally, ECMAScript format identifier using CamelCase
Identifier: refers to a variable name, function, property, or function parameter
small hump formula: lower case first letter of the first word, the first letter capitalized words behind the other;

eg:textHeight

Big Camel: every word in capital letters;

eg:TextHeigh

1.1 Variable

Naming method: small camel naming
naming convention: Prefix nouns

eg: let minCount = 10  let price = 100

Note: Global Variables word in all caps

eg:var PRICE = 100

1.2 Constant

Naming method: word all uppercase

eg: const PRICE = 100

1.3 Functions

Named functions should be able to depict the role and function of the function
name Method: Small camel naming
naming convention: verb prefix

Eg: function getHeight(){};
function setHeight(){};

1.4 class constructor

Naming methods: large camel naming
naming convention: Prefix Name

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

2 comments

2.1 Single-line comments

Description: single-line comment //
used: between comment codes (character) code to leave a space

More than 2.2-line comments

说明:多行注释以 /* 开头, */ 结尾
使用:若开始 /* 和结束*/都在一行,推荐采用单行注释。若至少三行注释时,第一行为 /*,最后行为 */

3 loose coupling

3.1html/js

Although born html and js interaction is required, but there are ways to be too closely coupled together, as follows

<button onClick="doSomething()">点击</button>

Tightly coupled as an event handler attribute value if there is a js problem, we should judge appears on the part of html or js files, thus affecting maintainability, or create a large number of structures in the js Dom

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

As the code problems. Navigate to this error is very difficult, because you first need to look at the source code page to find the insertion of this HTML, but can not find, because it is dynamically generated, if you change will require changes to the data or js layout, html rendering should 'as' separation and js.

3.2 css/js

Sometimes js css on too tight coupling
eg: trigger focus, change style

element.style.color = ‘red’;

If in the future need to change the style sheets, css and js files may need to be modified, which is not conducive to safeguarding the developers, so the need for a clear division between the two levels, so that coupling becomes loose some of it is as follows

element.className = ‘edit’;

Only modify an element of class css, js so you can change the style class, but will not directly affect the style element, any display problems can be traced back to css js instead, it will not be much better

3.3 application logic / event handling program coupled

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

In addition to this event handler event handling problems, this approach also has its own application logic dual nature, in addition to this first event there is no other way to do this through the application logic, if the code is a problem, it is out before calling the problems or issues arise in the application logic? It will make debugging difficult, if followed by subsequent events require the same logic, you need to put the code again in the copy, so we need a good solution
solution: the application logic and event handlers phase separation, the application packaged into a single logic function

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

4 semantic tags

Semantic means that one can see from the name what is, HTML tag that is able to see and what action is easy to understand by the element and attribute names, so good for the code better maintenance.
But when it comes for us this label from entering the school to the company's most newbies I can think of is the div tag + span tag, remember to do first came to the company to make an example of the time, from the use of labels to variables and function names and then to regulate between code, not a master will not let me a headache because of the time writing code too casual, too casual really, although now somewhat arbitrary Ha
If I write a page with all my might div tags, and even tag the id or name will only div1 div2 after written, and apparently this code is difficult to maintain, then if the label into

<header>,<nav>,<article>,<sections>,<aside>,<footer>

And other semantic tags will be a lot of code is not clear, as if this page is the navigation bar div, div sidebar is, the only distinction is that for div id, if a little ape program code specifications, may

<div id="nav"></div> 
<div id="aside"></div>

If casual style a little less attention to the code programmers probably what happened to the

<div id="div1"></div> 
<div id="div2"></div>

How about if you are to maintain this code, a month later you still remember div1, div2, what correspond to what, there is no gas to hit the wall, ha ha, so this time if you will not use the html5 tag will be much better

<nav></nav>
<aside>
    <span>答案略</span>
</aside>

Below that these few labels and usage probably say something

<header>:定义文档的页眉
  <header>
    <h1>wecome</h1>
    <p>My name is da dan</p>
  </header>
<nav>:标记链接的导航
  <nav>
    <a href="home.index">Home</a>
    <a href="personal.index">Personal</a>
  </nav>>
<article>规定独立的自包含内容(表示的是一个文档,页面,应用或是网站中的一个独立容器)
<sections>标签定义文档中的节(section、区段)。比如章节、页眉、页脚或文档中的其他部分,应用的典型场景(文章的章节,论文的编导,标签对话框的标签页)
注释:sections标签与article标签有点容易搞混,article代表一个的完整的相关的内容块而section只能算是整体的一部分
<article>
    <header>
      <h1>不要熬夜</h1>
      <p>
        <time pubdate datetime="2017/10/9"></time>
      </p>
    </header>
    <p>内容...</p>
    <section>
      <h1>评论区</h1>
      <article>
        <header>
          <p>评论者</p>
          <p>
            <time pubdate datetime="2017/10/10"></time>
          </p>
        </header>
        <p>评论内容</p>
      </article>
    </section>
  </article>

so read this example there is no clearer

<aside>侧栏标签(可用作文章的侧栏,广告,相关文章,新闻的链接)
  <aside>
    <h4>learn tools</h4>
    <p>小D词典</p>
    <p>开心词场</p>
  </aside>
<footer>定义文档或节的页脚,页脚通常包含作者信息,版权信息,使用条款链接,联系信息等等
<footer>
  <p>Posted by: author</p>
 </footer>
觉得还有一个挺好用的标签<figure>,它规定独立的流内容(图像,图表,照片,代码等)<figcaption>定义figure元素的标题
<figure>
  <figcaption>妹子</figcaption>
  <img src="girl.jpg" width="350" height="234" />
</figure>

5 Performance Optimization

5.1 Operating reduced DOM

Try not to use cycling DOM way, but at the end of the write cycle once.
eg: li want to dynamically inserting a plurality of child node ul

<ul id="ul">
</ul>

1. DOM mode loop operation

 window.onload = function(){
  var oUl = document.getElementById("ul");
for (var i = 0; i < 5; i++) {
   var oLi = document.createElement(“li”);
   oLi.innerText = i;
   oUl.appendChild(oLi);
}
}

2. The disposable insert

window.onload = function(){
  var oUl = document.getElementById("ul");
var aLi = “”;
for (var i = 0; i < 5; i++) {
   aLi += “li”;
   aLi += i;
   aLi += “li”;
}
oUl.innerHtml = aLi;
}

5.2 application event broker

Event bubbling -> event not only can handle the target on time, on target any ancestor node can handle. In the ancestor node binding event, only you need to operate a DOM, you can find the target node through the event flow, saving time to walk the child nodes, to bind to a large number of child nodes when the efficiency can be imagined.

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

1. traversing node binding event:
the window.onload = function () {

var oUl = document.getElementById("ul1");
var aLi = oUl.getElementsByTagName('li');
for(var i=0;i<aLi.length;i++){
    aLi[i].onclick = function(){
        alert(123);
    }
}

}
2. Using event delegation:

window.onload = function(){
  var oUl = document.getElementById("ul");
  oUl.onclick = function(ev){
    var ev = ev || window.event;
    var target = ev.target || ev.srcElement;
    if(target.nodeName.toLowerCase() == 'li'){
         alert(123);
         alert(target.innerHTML);
    }
  }
}

5.3 reference to the file:

The css file references on the head, a reference js file in the tail.
Browser rendering process, encountered js files will pause the current rendering process, the process of js precedence, while the top-down rendering of the document, if put into the js file header, it will affect the next DOM rendering. Typically, in a header file that alert, the browser will pop up alert dialog earlier, DOM rendering the next stop, there will be black and white phenomenon. There is another situation, js DOM document may alter the structure, typically have, document.write, this will cause unnecessary redraw and rearrangements.

Reduced rearrangement redraw 5.4

5.4.1 Repaint (redraw) is to be a change in appearance of the element, but does not change the case of the layout (width and height), such as changing the visibility, outline, and background colors.
5.4.2 Reflow (rearrangement) that change affects of DOM geometric properties of the element (width and height), the browser will recalculate the geometric properties of the element, it will render part of the tree affected by failure, the browser verifies DOM All other nodes of the visibility attribute of the tree, which is the reason Reflow inefficient. Such as: changing the window size of imports, change the text size, change, change browser window, change and much of the style attribute. If Reflow too often, CPU usage will go up the bass bass

In the following cases will be rearranged:
the initial page rendering
Add / Remove visible DOM element
to change the element position
changing element size (width, height, inner and outer margins, borders, etc.)
to change the element content (text or pictures, etc.)
to change the window size
2. by changing the style attribute setting style, then the node, each setting will lead to a reflow, so the best way by providing the class; animate element has its position property should be set to fixed or absolute, this will not affect other elements layout; if not set to fixed or absolute position on the functional requirements, then the smoothness of speed tradeoff.
How to reduce the rearrangement? Talk about my method:

1.分离读写操作
var curLeft=div.offsetLeft;
var curTop=div.offsetTop;
div.style.left=curLeft+1+'px';
div.style.top=curTop+1+'px';

2. You can add style to change the focus of a class, the style has changed in class
3. You can use absolute from the document flow.
4. display: none, without the use of visibility, and do not change the index-Z
5. The implementation can be to use CSS3 css3 achieved.

5.5 Other:

The combined picture (css sprites elves)
merge CSS and JS file
reduced picture resolution
to change the image format (png)
lower picture quality preservation
, etc.


I hope this article can be helpful to you, ah, refill

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12203761.html