This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Coding specification 1. HTML coding specification

  • 1. Code style

  • 1.1 Indent and line feed

[Force] Use 4 Spaces as a level of indentation. [Suggestion] Each line contains a maximum of 120 characters.

  • 1.2 named

[Mandatory] class The words must be lowercase and separated by hyphens (-). [Mandatory] The class must represent the content or functionality of the corresponding module or part and must not be named with style information. Element ID must be page unique. [Mandatory] Avoid using the same name and ID on the same page. [Suggestion] ID Recommended words Full subtitle Separate lowercase words with hyphens (-). The project must be consistent in style. [Suggestion] The name of the ID and class should be as short as possible on the premise of avoiding conflicts and making the description clear.

  • 1.3 the label

[Mandatory] The label name must use lowercase letters. [Mandatory] The label that does not need to be self-closed cannot be self-closed. Common tags that do not need self-closing include input, BR, img, and HR.

<input type="text" name="title">     //good
<input type="text" name="title" />     //bad
Copy the code

[Mandatory] It is not allowed to omit closed tags specified in HTML5. [Mandatory] Label usage must comply with the label nesting rules. For example, div must not be placed in p, and tbody must be placed in table.

  • 1.4 attributes

Attribute names must use lowercase letters. Such as:

<table cellspacing="0">.</table>    //good
<table cellSpacing="0">.</table>    //bad
Copy the code

Attribute values must be enclosed in double quotes. Such as:

<script src="babel.js"></script>    //good
<script src="Babel. Js'></script>     //bad
Copy the code

[Suggestion] Attribute of Boolean type. Do not add attribute value. [Suggestion] User-defined attributes You are advised to use data- and XXX – as the prefix.

  • 2. The general

  • 2.1 a DOCTYPE

Use HTML5 docType to enable standard mode. Uppercase doctype is recommended. [Suggestion] Enable the IE Edge mode.

<meta http-equiv="X-UA-Compatible" content="IE=Edge">
Copy the code

[Suggestion] Set the correct lang attribute on the HTML tag.

  • 2.2 coding

The page must be in compact mode with an explicit character encoding. The meta that specifies the character encoding must be the first direct child of head. [Suggestion] Use UTF-8 encoding of BOM for HTML files.

  • 2.3 Introduction of CSS and JavaScript.

When importing CSS, you must specify rel= “stylesheet”. [Suggestion] It is not necessary to specify the type attribute when importing CSS and JavaScript. [Suggestion] Add all CSS resources required by the page in the head. [Suggestion] JavaScript should be placed at the end of the page or loaded asynchronously.

  • 3.Head

  • 3.1 the title

The page must contain the title tag to declare the title. [Enforces] The title must be a direct child of the head and follow the charset declaration.

  • 3.2 the viewport

Suggestion: If the page is mobile-friendly, specify the viewport of the page.

  • Picture 4.

[Mandatory] Disable the value of SRC of img from being empty. Lazy-loaded images should also be added with the default SRC. [Force] Add Alt attribute to image. [Suggestion] Do not add unnecessary title attributes to img. [Suggestion] Use img tags for images that need to be downloaded, and use CSS background images for images that do not need to be downloaded.

  • 5. The form

  • 5.1 Control Title

A control with a text title must be associated with its label using the Label label. Two methods: 1. Place the control inside a Label. 2. The for property of the label points to the ID of the control.

  • 5.2 the button

The type attribute must be specified when using the button element. [Suggestion] Try not to use the name attribute of the button element.

  • 6. Multimedia

[Suggestion] When using the Audio and video tags to play audio and video in modern browsers, pay attention to the format. Audio formats: MP3, WAV, Ogg Video formats: MP4, WebM, Ogg [Recommended] Use audio and video tags in preference for HTML5 enabled browsers to define audio and video elements. [Suggestion] Enable automatic playback of audio and video only when necessary.

  • 7. HTML in the template

[Suggestion] Indentation of template code preferentially ensure the indentation rules of HTML code. [Suggestion] Template code should be based on the principle of ensuring the correctness of the syntax of each HTML tag. [Suggestion] If you need to output a fixed number of data in each row when constructing a table by cyclic processing template data, you are advised to group the data first and then cycle the output.

2. CSS coding specifications

  • 1. The name

  • 1.1 File Naming

Common file names: global: global.css Structure: Layout.css Module: module.css Theme: theme. CSS Long file names must be connected by a hyphen (-). Private style files in the project: project name – Service module name

  • 1.2 Selector naming

[force] Use id selectors when not necessary.

  • 1. The selector name is all lowercase, not uppercase.
  • 2. Use the -middle bar connection between longer selector names.
  • 3. When judging that naming conflicts are likely to occur, naming should follow the rules: module name – your selector name, if there are multiple levels of selector (should try to avoid more than 3 levels of selector), each level between the use of – crossbar, not recommended direct use of nesting.

[Suggestion] Name a common selector

  • 1 Code Style
  • 1.1 the indentation

[Mandatory] Use four Spaces for indent. Do not use TAB or two Spaces.

  • 1.2 the blank space

Selector must contain Spaces between {. Ex. :

/* good */
.selector {
}

/* bad */
.selector{
}
Copy the code

[Mandatory] There must be no space between an attribute and:, and there must be a space between: and an attribute.

.selector { color: white; } .selector { color:white; /* or color: white; * /}Copy the code

Leave a space on each side of the >, +, and ~ selectors.

  • 1.3 a newline

When there are multiple selectors in a rule, the selectors must be wrapped. Property values must be newline. [Suggestion] For excessively long style attribute values, wrap lines at Spaces or,.

  • 1.4 length

Each line must contain no more than 120 characters unless a single line is indivisible (for example, the URL is too long).

  • 2. Values and units

  • 2.1 the text

[Force] The text must be enclosed in double quotation marks.

  • 2.2 numerical

[Mandatory] If the value is between 0 and 1, omit the 0 part of the integer.

  • 2.3 units

[Mandatory] Property values with array 0 omit units.

  • 2.4 the url ()

[Mandatory] The path in the URL () function is not quoted. Suggestion: The absolute path in the URL () function can omit the protocol name.

  • 2.5 color

RGB color values must be in hexadecimal form #3f3f3f. RGB () is not allowed. Color information with alpha (opacity) can be used with RGBA (). When not using RGBA (), leave a space after each comma. [Mandatory] If the color value can be abbreviated, use the abbreviated form. [Mandatory] Color value Cannot use color words. (For example, red, green, etc.) [Suggestion] Use lowercase letters in the color value. If uppercase letters are used, they must be consistent within the same item.

  • 3. The general

  • 3.1 the selector

[Mandatory] The ID and class attributes of a DOM node cannot contain Spaces between =, and attribute values must be surrounded by double quotation marks (“) instead of single quotation marks (“). [Mandatory] If not necessary, do not use id selectors. When setting attributes for ID and class selectors, you do not need to add type selectors to qualify them. [Mandatory] Id selector does not need to be nested with other selectors.

  • 3.2 Attribute Abbreviations

[Suggestion] Use attribute abbreviations whenever possible. [Suggestion] When using abbreviations such as border, margin, and padding, use the abbreviations only when you need to set values in multiple directions to avoid overwriting useful values in other directions.

  • 3.3 Writing sequence of attributes

[Suggestion] Write in the following order:

1.Position properties (position, top, right, Z-index, display, float, overflow, etc.)2.Size (width, height, padding, margin, border)3.Text series (font, line-height, letter-spacing, color-text-align, etc.)4.Visual (background, color, list-style, etc.)5.Others (animation, transition, etc.)Copy the code
  • 3.4 Transformation and animation

[Mandatory] Specify transition-property instead of all when using transition.

  • 3.5 Attribute Prefix

[Suggestion] The private prefixes of attributes are arranged in order of length to length, as follows:

/* good */
.tab {
    -webkit-transition: color .5s;
       -moz-transition: color .5s;
            transition: color .5s;
}

/* bad */
/* bad */
.tab {
    -webkit-transition: color .5s;
    -moz-transition: color .5s;
    transition: color .5s;
}
Copy the code

Third, JavaScript coding specification

  • 1. Code style
  • 1.1 file

[Suggestion] Use UTF-8 encoding without BOM for JavaScript files. [Suggestion] Leave a blank line at the end of the file.

  • 1.2 the indentation

[Force] Use 4 Spaces as an indentation level. 2 Spaces or TAB characters are not allowed. [Mandatory] Case and default under switch must have an indent level added.

  • 1.3 the blank space

Binary operators must have a space on either side. Unary operators are not allowed to have a space between the operator and the object. [Force] Used as the opening curly brace {at the beginning of a code block must be preceded by a space. [force] if/else/for/while/function/switch/do/try/catch/finally keyword must be followed by a space. [Mandatory] When an object is created, : must be followed by a space, and: cannot be preceded by a space. In function declarations, named function expressions, and function calls, no Spaces are allowed between the function name and (. [compulsion], and; Spaces are not allowed before. In function calls, function declarations, parenthesis expressions, attribute access, if/for/while/switch/catch, etc., Spaces are not allowed in the parenthesis sections of () and []. [enforces] single-line declared arrays and objects. If they contain elements, {} and [] do not allow Spaces within the parentheses. No extra space at the end of a line.

  • 1.4 a newline

[Mandatory] Line breaks must follow the end of each independent statement. Each line contains a maximum of 120 characters. When the operator is newline, the operator must be at the beginning of the new line.

/* good */
var result = number1 + number2 + number3
+ number4 + number5;
/* bad */
var result = number1 + number2 + number3 +
number4 + number5;
Copy the code

In function declaration, function expression, function call, object creation, array creation, for statement, etc., cannot be in, or; Before the line break. [Suggestion] A set of statements with different behaviors or logic, separated by blank lines, is easier to read. [Suggestion] When the line length of a statement exceeds 120, indent the statement according to logical conditions. [Suggestion] For if… else… , try… catch… It is recommended to add a line break after the} sign to make the code hierarchy clearer and easier to read.

  • 1.5 the statement

[Mandatory] Do not omit the semicolon at the end of a statement. If/else/for/do/while statements do not omit the block {… }. Semicolons are not allowed at the end of function definition.

// In function expressions, semicolons are not allowed to be omitted.
var funcName = function() {};Copy the code

IIFE must be added to function expressions. Non-iife must not be added to function expressions. IIFE = Immediate-Invoked Function Expression (The code reads the example of the Function Invoked Immediately and understands the use of the following code. Rather than waiting until the bottom of the story.) Ex. :

// good
var task = (function () {
   // Code
   returnresult; }) ();var func = function () {};// bad
var task = function () {
    // Code
    returnresult; } ();var func = (function () {});Copy the code
  • 1.6 named

[Force] Variables to use Camel nomenclature. [Enforces] Use Camel naming for functions. [enforces] Use Camel nomenclature for the parameters of the function. [Enforces] Class parameters to use Camel nomenclature. Enforce Pascal naming for classes. [Enforces] Use Camel nomenclature for methods/attributes of classes. [Mandatory] Enumeration variables are named using Pascal nomenclature. Enumeration properties are named using all uppercase letters and underscore separated words. [Enforces] Use Camel for namespaces. [force] Abbreviation of more than one word, in naming, according to the current nomenclature and the position of occurrence, so that the case of the letter is consistent. Class names use nouns. [Suggestion] Use verb-object phrases for function names. [Suggestion] Boolean variables start with is or has. [误] I Promise you I’ll make a Promise.

  • 1.7 annotations

  • 1.7.1 Single-line comments

Mandatory The row must be exclusive. // Followed by a space, indented to match the next line of commented code.

  • 1.7.2 Multi-line comments

[Suggestion] Avoid using /… / Multiline comments like this. Use multiple single-line comments when you have multi-line comment content.

  • 1.7.3 Documented Comments

[Mandatory] For easy code reading and self-documentation, the following content must contain /**… */ block comments in the form. Explanation:

  1. File 2.namespace 3. class 4. function or method 5. Class attribute
  2. Event 7. global variables 8. constants 9. AMD modules

[Mandatory] A line must be left blank before a comment. [Suggestion] Change the document to describe what instead of how.

  • 1.7.4 Type Definition

Type definitions all start with {and end with}. Common types include: {string}, {number}, {Boolean},{Object},{Function},{RegExp},{Array},{Date}. [Mandatory] For basic types {string}, {number}, {Boolean}, the first letter must be lowercase.

  • 1.7.5 File Comments

[Mandatory] File comments must be included at the top of the file, using @file to identify the file description. Example:

/ * * *@file Describe the file
*/
Copy the code

[Suggestion] You can use @author to identify the developer information in the file comments. Names in @author are not allowed to be deleted. The fruits of any labor should be respected. 1.7.6 Namespace Comments [Suggestion] The namespace is identified by @namespace. Use @class to mark a class or constructor. Example:

/** * description **@class* /
function Developer() {
    // constructor body
}
Copy the code

Example: [Suggestion] Use @extends to mark inheritance information for a class.

/** * description **@class
 * @extends Developer* /
function Fronteer() {
    Developer.call(this);
    // constructor body
}
util.inherits(Fronteer, Developer);
Copy the code

Lendings When you expand the members of a class using the wrapper method, you must redirect the endings through the @lendings. Lendings You will not be able to generate the document that contains the members of the extended class for this class without the @lendings tag. [Mandatory] Member information such as attributes or methods of a class uses either @public / @protected / @private to indicate accessibility. Example:

/** * class description **@class
* @extends Developer* /
function Fronteer() {
Developer.call(this);
// constructor body
}

util.extend(
Fronteer.prototype,
/ * *@lends Fronteer.prototype */{
_getLevel: function () {
// TODO}});Copy the code

Member information such as attributes or methods of a class uses one of @public / @protected / @private to indicate accessibility. Example:

/** * class description **@class
 * @extends Developer* /
var Fronteer = function () {
    Developer.call(this);

    /** * Attribute description **@type {string}
     * @private* /
    this._level = 'T12';

    // constructor body
};
util.inherits(Fronteer, Developer);
Copy the code
/** * method description **@private
 * @return {string} Return value description */
Fronteer.prototype._getLevel = function () {};Copy the code
  • 1.7.8 Function/method comments

Mandatory Function/method comments must contain function declarations and must be marked with comments if they have arguments and return values. Parameter and return value comments must contain type information and description. Suggestion: If a function is internal and cannot be accessed from outside, use @inner. [Mandatory] The @param identifier must be used to describe items in Object.

/** * function description **@param {Object} Option Parameter description *@param {string} Option. url Description of the option option *@param {string=} Option. method Specifies the option option. */ is optional
function foo(option) {
    // TODO
}
Copy the code
  • 1.7.9 Event Notes

[Mandatory] @event must be used to identify events. The identifiers of event parameters are the same as those in the method description. [Mandatory] Use @Fires before functions that broadcast events and @event before event codes to identify events. [Suggestion] For comments on event objects, use @param to make the generated document more readable.

  • 1.7.10 Constant comments

Constants must use the @const tag and contain description and type information. Example:

/** * Constant description **@const
 * @type {string}* /
var REQUEST_URL = 'myurl.do';
Copy the code
  • 1.7.11 Complex Type Annotation

[Suggestion] For comments of complex structures whose type is not defined, you can use the @typedef identifier to define them.

  • 1.7.12 COMMENTS on AMD Modules

AMD modules use @Module or @exports logo. [Mandatory] Module: must be prefixed with @ Module in namepaths for AMD module references.

  • 1.7.13 Detail notes

[Suggestion] Follow the format of a single line comment. Specifies that when line breaks are required, each line is the start of a single-line comment. [Mandatory] Sometimes we use special tokens to illustrate. Special tags must use single-line comments. Common marks:

  1. TODO: Features waiting to be implemented. In this case, a brief description of the functions to be implemented is required.
  2. FIXME: This code allows no problems, but may need to be fixed due to time constraints or other reasons. A brief explanation of how to fix it is needed.
  3. HACK: code that is poorly written to fix a problem or uses some weird trick. A description of the train of thought or the strange method is needed.
  4. XXX: There is a defect there. The trap needs to be described.

2 Language Features

  • 2.1 variable

Variables must be defined by var before they can be used. Only one variable can be declared per var. Variables must be declared immediately and must not be declared uniformly at the start of a function or other code block. Explanation: The more distant a variable declaration is from use, the greater the span of occurrence, and the higher the cost of code reading and maintenance. Although JavaScript variables are function scoped, the distance between variables should be reduced according to programming intent. Example:

// good
function kv2List(source) {
    var list = [];

    for (var key in source) {
        if (source.hasOwnProperty(key)) {
            var item = {
                k: key,
                v: source[key] }; list.push(item); }}return list;
}

// bad
function kv2List(source) {
    var list = [];
    var key;
    var item;

    for (key in source) {
        if (source.hasOwnProperty(key)) {
            item = {
                k: key,
                v: source[key] }; list.push(item); }}return list;
}
Copy the code
  • 2.2 conditions

[Force] Use type strict === in Equality Expression. == null is allowed only for null or undefined. [Suggestion] Use brief expressions whenever possible. Example:

// The string is empty

// good
if(! name) {/ /...
}

// bad
if (name === ' ') {
    / /...
}

// The string is not empty

// good
if (name) {
    / /...
}

// bad
if(name ! = =' ') {
    / /...
}

// The array is not empty

// good
if (collection.length) {
    / /...
}

// bad
if (collection.length > 0) {
    / /...
}

// good
if(! notTrue) {/ /...
}

// bad
if (notTrue === false) {
    / /...
}

/ / null or undefined

// good
if (noValue == null) {
  / /...
}

// bad
if (noValue === null || typeof noValue === 'undefined') {
  / /...
}
Copy the code

[Suggestion] Arrange branches by execution frequency. Explanation: The advantages of ordering branches by frequency of execution are:

  1. Easy to find the most common cases, increase readability.
  2. Improve execution efficiency.

[Suggestion] Replace if with switch for multi-valued conditions of the same variable or expression. Example:

// good
switch (typeof variable) {
    case 'object':
        / /...
        break;
    case 'number':
    case 'boolean':
    case 'string':
        / /...
        break;
}

// bad
var type = typeof variable;
if (type === 'object') {
    / /...
} 
else if (type === 'number' || type === 'boolean' || type === 'string') {
    / /...
}
Copy the code

[Suggestion] If there is no statement after the else block in function or global, delete the else block.

  • 2.3 cycle

Do not include function expressions in the body of the loop. Extract the functions out of the loop beforehand. Explanation: the function expression in the loop body, the running process will generate a number of loop function objects. Example:

// good
function clicker() {
    / /...
}

for (var i = 0, len = elements.length; i < len; i++) {
    var element = elements[i];
    addListener(element, 'click', clicker);
}


// bad
for (var i = 0, len = elements.length; i < len; i++) {
    var element = elements[i];
    addListener(element, 'click'.function () {});
}
Copy the code

[Suggestion] Use variable caching outside the loop for constant values that are used multiple times within the loop. [Suggestion] Iterate the ordered set and cache the length. [Suggestion] Use reverse order traversal to perform an ordinary-independent traversal of an ordered set. Reverse traversal can save traversal, code optimization. Example:

var len = elements.length;
while (len--) {
    var element = elements[len];
    / /...
}
Copy the code
  • 2.4 type

  • 2.4.1 Type Detection

Suggestion: Typeof is preferred for type detection. Object type detection uses Instanceof. Null or undefined is detected using ==null.

  • 2.4.2 Type Conversion

[Suggestion] When converting to string, use + ‘. [Suggestion] When converting to number, usually use +. [Suggestion] Convert string to number. Use parseInt if the string to be converted has a non-number at the end and you expect to ignore it. Example: var width = ‘200px’; parseInt(width, 10); [Mandatory] If parseInt is used, the base must be specified. Example: // good parseInt(STR, 10);

// bad parseInt(str); [Suggestion] When converting to Boolean, use!! . Var num = 3.14; !!!!! num; Math.floor/math.round/math.ceil, not parseInt.

  • 2.5 the string

[Force] String begins and ends with single quotation marks’. Explanation:

  1. You don’t need to hold shift to enter single quotes.
  2. In practice, strings are often used to concatenate HTML. You don’t need to escape to include double quotes in HTML.

[Suggestion] Use the + concatenation string. [Suggestion] Choose a template engine for complex data to view string conversion process.

  • 2.6 object

Using an object literal {} creates a new object. [Mandatory] If all attributes of an object can be created without quotation marks, they cannot be quoted. [Force] When an object is created, if any attributes need to be quoted, all attributes must be quoted ‘. It is not allowed to modify or extend the prototype of any native or host object. Example: // The following behaviors are strictly prohibited

String.prototype.trim = function () {};Copy the code

[Suggestion] Use. When accessing properties. Explanation: Attribute names that meet the Identifier requirement can be used by. Otherwise, you can only access it through [expR]. For objects declared in JavaScript, attribute naming is done using Camel nomenclature, using. To make access clear and concise. Some special attributes, such as JSON from the back end, may be named in an unusual way and can be accessed through [expr]. Example: the info. The age; info[‘more-info’]; [Suggestion] For in When traversing objects, use hasOwnProperty to filter out attributes in the prototype. Example:

var newInfo = {};
for (var key in info) {
    if(info.hasOwnProperty(key)) { newInfo[key] = info[key]; }}Copy the code
  • 2.7 an array

[forces] To create a new array using an array literal [], unless you want to create an array of specified length. [Mandatory] Traversal number groups do not use for in. [Suggestion] Do not implement the array sort function for performance reasons. Try to use the array sort method. Explanation: The general sort algorithm implemented by myself is no better than the default sort method for arrays in terms of performance. There are two scenarios where you can sort by yourself:

  1. Stable sorting algorithm is needed to achieve strictly consistent sorting results.
  2. Distinctive data characteristics, suitable for the use of bucket row.

[Suggestion] Case array use.length = 0.

  • 2.8 the function

  • 2.8.1 Length of function

Limit the length of a function to 50 lines or less.

  • 2.8.2 Parameter design

[Suggestion] Limit the number of parameters in a function to six. Explanation: In addition to variable length parameters, it is recommended to control the parameters with different logical meanings within 6, too many parameters will lead to increased maintenance difficulty. In some cases, such as using THE AMD Loader require to load multiple modules, the callback may have many parameters, so the number of function parameters is not mandatory. [Suggestion] Pass non-data input parameters through the options parameter.

  • 2.8.3 closure

[Suggestion] Set the inside closure object to NULL when appropriate. 2.8.4 Empty Functions [Suggestion] Empty functions do not use the form new Function(). Example: the javascript

var emptyFunction = function () {};
Copy the code

[Suggestion] For scenarios with high performance requirements, it is recommended to have an empty function constant for multiple use and sharing.

  • 2.9 Object-oriented

Class inheritance scheme, implemented with correction for constructor. Explanation: Class inheritance schemes using other libraries usually do constructor corrections. If you implement your own class inheritance scheme, you need to make a constructor correction. Example:

/** * Build inheritance relationships between classes **@param {Function} SubClass subClass function *@param {Function} SuperClass superClass function */
function inherits(subClass, superClass) {
    var F = new Function(a); F.prototype = superClass.prototype; subClass.prototype =new F();
    subClass.prototype.constructor = subClass;
}
Copy the code

[suggestion] When declaring a class, ensure that the constructor is correct. Example:

function Animal(name) {
    this.name = name;
}

Constructor needs to be fixed when direct prototype equals the object
Animal.prototype = {
    constructor: Animal,

    jump: function () {
        alert('animal ' + this.name + ' jump'); }};// Extend prototype this way without bothering with constructor
Animal.prototype.jump = function () {
    alert('animal ' + this.name + ' jump');
};
Copy the code

[Suggestion] Properties are declared in constructors and methods are declared in stereotypes. Explanation: Members of the prototype object are shared by all instances, saving memory. So when coding, we should follow the principle that prototype objects contain members that the program will not modify, such as method functions or configuration items.

function TextNode(value, engine) {
    this.value = value;
    this.engine = engine;
}

TextNode.prototype.clone = function () {
    return this;
};
Copy the code

[Mandatory] User-defined event names must be all lowercase. Custom events can have only one event parameter. If an event needs to convey a lot of information, the event object should be carefully designed. [Suggestion] Disable the default behavior when designing custom events. Explanation: There are two common ways to disable default behavior:

  1. Return false in event listener functions.
  2. The event object contains methods to disable the default behavior, such as preventDefault.
  • 2.10 Dynamic Features

  • 2.10.1 eval

Avoid using direct eval functions. Try to avoid using the eval function.

  • 2.10.2 Dynamic code execution

[Suggestion] Use new Function to execute dynamic code. The scope of a Function generated by new Function is global and does not affect the current local scope. If dynamic code execution is required, new Function is recommended. Example:

var handler = new Function('x'.'y'.'return x + y; ');
var result = handler($('#x').val(), $('#y').val());
Copy the code
  • 2.10.3 with

[Suggestion] Try not to use with. Explanation: Using with may increase code complexity and make it difficult to read and manage. It also has an impact on performance. Most scenarios that use with can be better served by other alternatives. So, try not to use with.

  • 2.10.4 delete

[Suggestion] Reduce the use of DELETE. Explanation: If there are no specific requirements, reduce or avoid the use of DELETE. The use of DELETE can break some of the performance optimizations of JavaScript engines.

  • 2.10.5 Object Properties

[Suggestion] Do not modify external parameters. [Suggestion] Design with strong type.

  • 3. Browser environment

  • 3.1 modular

  • 3.1.1 AMD

[Force] Use AMD as module definition. Explanation: AMD is a community-approved form of module definition that offers multiple overloads and flexible usage, and most good libraries support AMD as a suitable specification. At present, the more mature AMD Loader has:

  1. The official implementation require.js
  2. Baidu’s own esl implementation

[Mandatory] The module ID must meet the standard. Explanation: The module ID must meet the following constraints:

  1. It is of type string and consists of a series of terms separated by /. For example: this/is/a/module.
  2. Term should comply with the [A-ZA-Z0-9_ -]+ rule.
  3. There should be no.js suffix.
  4. Keep it the same as the file path.
  • 3.1.2 define

[Suggestion] Do not specify ID and dependencies when defining modules. Explanation: In AMD’s design philosophy, module names are associated with the path, and anonymous modules are better for encapsulation and migration. Module dependencies should be referenced within the module definition via local require. Therefore, it is recommended to define modules in the form of define(Factory). [Suggestion] Use return to return the module definition.

  • 3.1.3 the require

[Mandatory] In a global runtime environment, require must be called as async require. Description: Modules load asynchronously, require must be called async require.

[Mandatory] Only local require is allowed in the module definition, not global require. Explanation: Using global require in a module definition is a violation of encapsulation. In AMD, global Require can be renamed. And Loader does not even have a global require variable, but uses the Loader name as global require. Module definitions should not depend on the Loader being used.

[Mandatory] When the Package is implemented, the internal module require must use relative ID. Explanation: The name defined by the developer does not represent the name used by the consumer for any third-party library, framework, or package that may be reused in a publish-import format. So don’t make any assumptions about names. In the implementation source code, require other modules of its own use relative ID.

[Suggestion] dependency modules that will not be called, uniform require at the start of factory. Explanation: Some modules are dependent modules that are not called directly in a module implementation, most typically external content introduced by plugins such as CSS/JS/TPL. This kind of content is recommended to be referenced uniformly at the beginning of the module definition.

  • 3.2 the DOM

  • 3.2.1 Element Acquisition

For individual elements, use document.getelementByID instead of document.all. [suggestion] for a collection of multiple elements, as far as possible using the context. The getElementsByTagName to obtain. Where context can be document or something else. Specifying the tagName argument to * gets all child elements. [Suggestion] Cache the set length as much as possible when traversing the set of elements. If you need to manipulate the same collection more than once, you should turn the collection into an array.

  • 3.2.2 Style Acquisition

Suggestion: Use getComputedStyle or currentStyle to obtain the actual element style information.

  • 3.2.3 Style Settings

If possible, change the style of an element by adding a predefined className to the element, avoiding direct manipulation of the style setting. [Force] When styling an element with a style object, it is not allowed to omit units for attributes with non-zero unit values.

  • 3.2.4 DOM manipulation

[Suggestion] When operating the DOM, minimize page reflow. Explanation: Page reflow is a very time consuming behavior that can easily lead to performance bottlenecks. The following scenarios trigger reflow in the browser:

  1. Add, modify (content), and delete DOM elements.
  2. Apply new styles or modify any attributes that affect the layout of elements.
  3. Resize browser window and scroll page.
  4. Read the elements of certain attributes (offsetLeft and offsetTop, offsetHeight, offsetWidth, scrollTop/Left/Width/Height, clientTop/Left/Width/Height, getCompu TedStyle (), currentStyle(in IE)).

[Suggestion] Minimize DOM operations. Explanation: DOM manipulation is also a time-consuming operation, and reducing DOM manipulation can help improve performance. As a simple example, build a list. We can do this in two ways:

  1. CreateElement in the body of the loop and append to the parent element.
  2. Concatenate the HTML string in the body of the loop, and write the innerHTML of the parent element after the loop ends.

The first approach looks standard, but the DOM is manipulated every time the loop is used, and performance is extremely low. The second approach is recommended here.

  • 3.2.5 DOM events

[Suggestion] Preferentially use addEventListener/attachEvent to bind events. Avoid binding events of expando attributes in HTML attributes. Explanation: The expando attribute binds events easily to overwrite each other.

[Suggestion] Use false for the third parameter when using addEventListener. Explanation: The addEventListener in standard browsers can specify two time-triggered models with a third parameter: bubbling and capturing. IE attachEvent supports only bubbling events. So for consistency, the third argument to addEventListener is usually false.

[Recommendation] Without the support of an automatic event management framework, you should hold a reference to the listener function and remove the added listener when appropriate (element release, page unload, etc.).