V1.3 @ Suming Lv


(TOC) directory

0.0 General Principles

0.1 Core Idea

Separation of performance, content and behavior. Tags should be well-structured, semantically correct, and generally legal. Incremental enhancement to improve the user experience.

0.2 Basic Principles

Code consistency: By keeping code style and tradition consistent, we can reduce the burden of legacy system maintenance and reduce the risk of future system crashes. Best practices: By following best practices, we can ensure optimized page loading, performance, and maintainable code.

0.3 Application Principles

If there is no special description in this specification, please refer to the implementation. * is recommended and ** is required

1.0 Naming Rules

1.1 Project Name

  • Use lowercase characters and delimit by hyphens. It cannot contain Chinese characters, Spaces and special characters
  • Avoid single-letter naming. Naming should be descriptive

Example: my project — the name

1.2 Directory Naming

Refer to project naming rules;

When there is a complex number structure, use the plural nomenclature.

Examples: scripts, styles, images, data-models

1.3 File Naming

Dynamic language file naming principle, described by property _, description can have multiple words, separated by “_”, the property is generally the summary of the page. For example, the HTML file is named error-report. HTML JS file is named account-model. JS CSS, and LESS file is named retina-sprites.less

  • Use index.html index.htm index.asp file name (in this order)
  • If the name is many and complex and not good to be named by English words, use the name pinyin or the first letter of pinyin
  • Don’t use abbreviations unless they are conventional

1.4 HTML named

Refer to project naming and file naming rules.

1.5 JS naming

Refer to project naming and file naming rules.

1.5.1 Naming functions

  • Name objects, functions, and instances in small camel case.
  • Use an underscore _ to name private attributes.

1) Methods that get individual objects are prefixed with get. 2) Get multiple object methods prefixed with list. 3) Methods to obtain statistics are prefixed with count. 4) Insert methods are prefixed with save (recommended) or insert. 5) Delete methods are prefixed with remove (recommended) or delete. 6) Modify methods prefixed with set (recommended) or update.

1.5.2 Paging naming

2) Response value: total (total pages, default 0)

1.5.3 other

Description: Any class, method, parameter, variable, strictly control access scope. Too wide access range is not conducive to module decoupling.

1.6 CSS: Named LESS

Refer to project naming and file naming rules.

2.0 HTML

2.1 grammar

Try to use semantic tags with four Spaces instead of tabs. Nested elements should be indented once (that is, four Spaces). For attributes, be sure to use double quotes all the time, not single quotes. Do not add slashes to the end of self-closing elements. IMG element annotated with Alt. Add comments for more than 12 lines of element blocks or key logic, all in the following format.

<! -- comment Begin --> ... <! -- comment Begin -->Copy the code

When inserting JS into HTML, add space before and after the paragraph delimiter using the actual

element, not multiple

tags. Where appropriate, make full use of the < DL > (define list) and < blockQuote > tags. Entries in a list must always be placed in

    , < OL >, or < DL > and never represented by a set of

    or

    . Add a

    tags to indicate what element is closed here. This can be useful in cases where there is a lot of nesting and indentation. Do not use tables for page layout. When appropriate, use microformats and/or Microdata, hcards and ADR. Use the , < tBody >, and tags (as well as the Scope attribute) when appropriate. Avoid using outdated tags, such as
    , , < I >, and use , instead. Use data-xxx to add custom data, for example, . For other character entities, see: Character Entities

2.2 HTML Doctype

HTML5 defaults to

2.3 the lang attribute

HTML tags should have lang attributes.

2.4 meta

Use the meta as required. For details, see cool-head Demo:

<meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="Cache-Control" content="max-age=7200" /> <meta name="viewport" content="width=device-width, <link rel="shortcut icon" href="favicon.ico"> <link rel="apple-touch-icon" href="/apple-touch-icon.png">Copy the code

2.5 IE Compatible Mode

Use the
tag to specify which version of IE the page should be rendered with;

2.6 Introduce CSS and JavaScript files

According to the HTML5 specification, it is generally not necessary to specify the type attribute when importing CSS and JavaScript files, since text/ CSS and text/ JavaScript are their default values, respectively.

2.7 Attribute order *

Attributes should appear in a specific order to ensure readability;

class  
id  
name  
data-*  
src, for, type, href, value , max-length, max, min, pattern  
placeholder, title, alt  
aria-*, role  
required, readonly, disabled  
Copy the code

[//]: # class is designed for highly reusable components, so should be in the first place; [//]: # id is more specific and should be used sparingly, so put it in second place.

2.8 Boolean attribute

Boolean attributes are attributes that do not require a value to be declared. XHTML requires a value for each attribute, but HTML5 does not.

<input type="text" disabled>
<input type="checkbox" value="1" checked>
<select>
    <option value="1" selected>1</option>
</select>
Copy the code

2.9 JS generates labels

Generating tags in JS files makes content harder to find, harder to edit, and worse performance. This should be avoided as much as possible.

2.10 Reducing the number of Labels

When writing HTML code, you need to avoid redundant parent nodes; Many times, you need to iterate and refactor to make HTML less.

2.11 Practical over perfect

Try to follow HTML standards and semantics, but not at the expense of usability; Solve problems with as little complexity and as few tags as possible at all times.

3.0 CSS, SCSS, LESS

Use normalize.css to make rendering more consistent across browsers

3.1 the indentation

Use 4 Spaces.

3.2 the semicolon

Each property declaration ends with a semicolon.

3.3 the blank space

Spaces are not required in the following cases:

Attribute names are followed by multiple rule delimiters ‘,’ before! important ‘! Do not have extra Spaces at the end of the line before ‘(‘ and ‘)’ in ‘after’ attribute values:

Property values before selectors ‘>’, ‘+’, ‘~’ before and after ‘{‘ before! important ‘! ‘before @else ‘,’ after comment ‘/’ and ‘/’ before attribute values

3.4 a blank line

Blank lines are required in the following cases:

At the end of the file, it is best to reserve a blank line ‘}’ followed by a blank line, including an appropriate blank line between nested rule attributes in less, see attribute declaration order

3.5 a newline

A line break is not required in the following cases: before ‘{‘

Newlines are required in the following cases: after ‘{‘ and ‘}’ each attribute is exclusive to a line of multiple regular delimiters ‘, after ‘

3.6 annotations

Use ‘/* */’ for comments (not ‘//’ in less or SCSS). Indent the same as the next line of code; Can be at the end of a line of code, separated by a space from the code.

3.7 the quotation marks

Use double quotation marks on the outermost layer; The content of the URL should be quoted; Attribute values in attribute selectors need quotes.

3.8 named

Class names are all lowercase letters separated by a dash, and ids are camel-shaped. Variables, functions, blends, and placeholder in LESS or SCSS are camel-shaped

3.9 Order of attribute declaration *

Related attribute declarations are grouped in the following order, with a blank line between the groups. Layout positioning attributes – > own attributes – > Text attributes – > Other attributes Layout positioning attributes mainly include: Margin, padding, float (clear), position (top,right,bottom,left), display, visibility, overflow, etc. Its attributes mainly include: width & height & background & border; Text attributes mainly include: font, color, text-align, text-decoration, text-indent, etc. Other properties include: list-style, vertical-vlign, CURSOR, Z-index, and ZOOM CSS Description Refer to the recommended CSS property sequence

3.10 color

Color hexadecimal lowercase letters; Use abbreviations for hexadecimal colors. Translucent effects use RGBA format.

3.11 Shorthand for Attributes

Property abbreviations require you to be very clear about the correct order of property values, and in most cases you do not need to set all the values contained in property abbreviations, so separate declarations are recommended to be clearer; Margin, as opposed to padding, needs to be abbreviated; Common property abbreviations include: Font background transition animation

3.12 Media Query

Try to keep the rules for media queries close to the rules related to them, and don’t put them together in a separate style file or at the bottom of the document, which only makes it easier for people to forget them later.

.element { ... } .element-avatar{ ... } @media (min-width: 480px) { .element { ... } .element-avatar { ... }}Copy the code

3.13 LESS or SCSS related

Declaration order:

@extend that does not include @content @include that does include @content nested rules for @include’s own attributes @import introduces files that do not need to start with ‘_’ and end with ‘.scss’;

Placeholder selectors are used in @extend;

Don’t publish code with @import and @debug;

Remove unnecessary parent reference symbol ‘&’.

3.14 other

The rule of not being available;

Element selectors are lowercase;

Remove the 0 in front of the decimal point;

Remove unnecessary decimal points and trailing zeros from numbers;

Attribute value ‘0’ is not followed by a unit;

Different prefixes for the same attribute should be aligned vertically, as shown on the right;

Standard attributes without prefixes should be written after prefixed attributes;

Do not have duplicate attributes in the same rule. It does not matter if the repeated attributes are contiguous.

Don’t have two rules in the same file;

With the border: 0; Instead of the border: none; ;

No more than 4 layers of selectors (in SCSS if more than 4 layers should be considered nested);

Minimize the use of ‘*’ selectors;

Chinese characters (such as font names) in the CSS must be converted to Unicode codes.

Large block styles must be commented and small blocks annotated appropriately.

4.0 JavaScript

4.1 the indentation

  • Use 4 Spaces
  • Don’t mix tabs and Spaces;
  • Don’t use multiple tabs or Spaces in one place;

4.2 Single line length

  • Do not exceed 80 and use string join numbers (single-line lengths are not considered for Word wrap).
  • When generating strings programmatically, use template strings instead of string concatenations.
// good
function sayHi(name){
    return `How are you ${name}?`
}
Copy the code

4.3 the semicolon

Each line of logic should end with a semicolon

4.4 the blank space

Spaces are not required in the following cases:

Object attribute names are prefixed with unary operators postfixed with unary operators before function calls before parentheses, function declarations and function expressions are preceded by ‘(‘ not by the ‘[‘ and ‘]’ of whitespace arrays before the ‘{‘ and ‘}’ of objects before the operators ‘(‘ and ‘)’

Spaces are required in the following cases:

Binary operator before and after the ternary operator ‘? :’ before and after block ‘{‘ before the following keywords: else, while, catch, finally after the following keywords: If, else, for, while, do, switch, case, try, catch, finally, with, return, typeof single line comment after ‘//’, Multiple lines of comment ‘*’ followed by a semicolon followed by a space for the property value of the object. If there are multiple preconditions, a space followed by a comma must be placed between the arguments of a function declaration or function expression

// not good var a = { b :1 } // good var a = { b: 1 } // not good ++ x y ++ z = x? 1:2 // good ++x y++ z = x ? 1: 2 // not good var a = [ 1, 2 ] // good var a = [1, 2] // not good var a = ( 1+2 )*3 // good var a = (1 + 2) * 3 // no space before '(', one space before '{', one space between function parameters var doSomething = function(a, b, c) { // do something } // no space before '(' doSomething(item) // not good for(i=0; i<6; i++){ x++ } // good for (i = 0; i < 6; i++) { x++ }Copy the code

4.5 a blank line

Blank lines are required in the following cases:

  • After a variable is declared (blank lines are not required when the variable is declared on the last line of the code block)
  • Before the comment (blank lines are not required when the comment is on the first line of the code block)
  • After a block of code (no blank lines in function calls, arrays, objects)
  • Leave a blank line at the end of the file

4.6 a newline

Line breaks are not required in the following cases:

  • Else, catch, finally
  • Code block ‘{‘ before

Line breaks are required in the following cases:

  • Code blocks ‘{‘ after and ‘}’ before
  • After the variable is assigned
  • After the comma
  • The expression exceeds or is about to exceed the specified column width (the code column width is controlled to be around 110 or 120 characters). Indent the second line by 4 Spaces relative to the first line, starting with the third line, and no further indentation
  • The operator is wrapped before the operator, the operator is wrapped with the context, and the dot symbol of the method call is wrapped with the context
// not good var a = { b: 1 , c: 2 }; x = y ? 1:2; // good var a = { b: 1, c: 2 }; x = y ? 1:2; x = y ? 1:2; // no need line break with 'else', 'catch', 'finally' if (condition) { ... } else { ... } try { ... } catch (e) { ... } finally { ... } // not good function test() { ... } // good function test() { ... } // not good var a, foo = 7, b, c, bar = 8 // good var a, foo = 7, b, c, bar = 8Copy the code

4.7 One-line comments

A double slash must be followed by a space;

Indent the same as the next line of code;

Can be at the end of a line of code, separated by a space from the code.

4.8 Multi-line comments

At least three lines with ‘*’ followed by a space, as shown on the right;

It is recommended to be used in the following situations:

Difficult to understand code segments that may have errors Browser specific HACK code business logic strongly related code

/*
 * one space after '*'
 */
var x = 1
Copy the code

4.9 Document Comments

Please refer to JSDoc Chinese, USEJsDoc and JSDoc Guide for tags @param, @Method, etc.

It is recommended to be used in the following situations:

All constants all functions all classes

/** * @func * @desc A function with arguments * @param {string} a - parameter a * @param {number} b=1 - Parameter b default value is 1 * @param {string} c=1 - There are two supported values of parameter c: 1 - for x 2 - for xx * @param {object} d - For an object * @param {string} d.e - for the e attribute of parameter d * @param {string} d.f - for the F attribute of parameter d * @param {object[]} g - parameter g is an object array * @param {string} g.h - parameter g in the array h attribute * @param {string} g.i - parameter g in the array I attribute * @param Function foo(a, b, c, d, g, j) {/ / function foo(a, b, c, d, g, j) {... }Copy the code

4.10 the quotation marks

Use single quotation marks for the outermost layer.

4.11 Variable Naming

Standard variables are named in camel case (except for the attributes of the object, mainly because of the data returned by cgi) ‘ID’ all uppercase in the variable name ‘URL’ all uppercase in the variable name ‘Android’ uppercase the first letter in the variable name ‘iOS’ all uppercase in the variable name, Join constructors with an underscore, capitalizing the first letter of the jquery object must be named beginning with ‘$’

var thisIsMyName;

var goodID;

var reportURL;

var AndroidVersion;

var iOSVersion;

var MAX_COUNT = 10;

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

// not good
var body = $('body');

// good
var $body = $('body');
Copy the code

4.12 Variable declaration

  • Use function declarations instead of function expressions.
  • All variable declarations in a function scope refer to the header of the function as much as possible. Use a single var or let declaration.
  • Use abbreviations of object attribute values and group the attributes of the abbreviations.
const name = 'name'; const age = 'age'; // const obj = function(){} // good const obj = {name, age, sex: 'male ', height: '170'}Copy the code
  • Use deconstruction to access and use multi-attribute objects. Because deconstruction reduces the number of temporary references to attributes.
// bad
function getFullName(user){
    const fileName = user.firstName;
    const lastName = user.lastName;
    
    return `${firstName} ${lastName}`
}

// good
function getFullName(user){
    const { firstName, lastName } = user;
    
    return `${firstName} ${lastName}`
}

// best
function getFullName({ firstName, lastName }){
    return `${firstName} ${lastName}`
}
Copy the code

4.13 the function

References to context this can only be named ‘_this’, ‘that’, or ‘self’;

Do not name inline functions;

Arguments are separated by ‘, ‘, and note that there is a space after the comma.

Specify default values for function arguments. Do not use a variable function argument.

// bad
function handleThings(opts){
    opts = opts || {};
}

// good
function handleThings(opts = {}){ 
}
Copy the code

4.14 Arrow function

  • Use the arrow function notation when you must use a function expression (or pass an anonymous function). Since the arrow function creates a new context for this execution, it usually works for your needs and is much simpler to write.
// bad
[1, 2, 3].map(function (x) {
    return x * x;
})

// good
[1, 2, 3].map(x => {
    return x * x;
})
Copy the code
  • If a function is suitable for a single line and has only one argument, omit the curly braces, parentheses, and return. If not, don’t omit it.
// good
[1, 2, 3].map(x => x * x);

// good
[1, 2, 3].map((total, x) => {
    return total + x;
})
Copy the code

4.15 Constructor

  • Always use class and avoid manipulating Prototype directly.
// bad function Queue(contents = []){ this._queue = [...contents]; } Queue.prototype.pop = function(){ const value = this._queue[0]; this._queue.splice(0, 1); return value; } // good class Queue { constructor(contents = []){ this._queue = [...contents]; } pop(){ const value = this._queue[0]; this._queue.splice(0, 1); return value; }}Copy the code
  • Use extends inheritance. Extends is a built-in prototype inheritance method that does not break Instanceof.
// bad const inherits = require('inherits'); function PeekableQueue(contents) { Queue.apply(this, contents); } inherits(PeekableQueue, Queue); PeekableQueue.prototype.peek = function() { return this._queue[0]; } // good class PeekableQueue extends Queue { peek() { return this._queue[0]; }}Copy the code
  • The method can return this to aid in chain calls.
// bad
Jedi.prototype.jump = function() {
    this.jumping = true;
    return true;
};

Jedi.prototype.setHeight = function(height) {
    this.height = height;
};

const luke = new Jedi();
luke.jump(); // => true
luke.setHeight(20); // => undefined

// good
class Jedi {
    jump() {
        this.jumping = true;
        return this;
    }
    
    setHeight(height) {
        this.height = height;
        return this;
    }
}

const luke = new Jedi();

luke.jump().setHeight(20);
Copy the code

4.16 Arrays and objects

Object attribute names do not need to be quoted;

Write objects indented, not on a single line;

Arrays and objects should not end with commas.

4.17 the brackets

Braces must follow the following keywords (even if the block is only one line) : if, else, for, while, do, switch, try, catch, finally, with.

4.18 the null

Applicable scenarios:

Initialize a variable that may be assigned to an object in the future compared to a variable that has already been initialized as a parameter to a call to a function that returns an object

Not applicable scenarios:

Do not use null to determine whether a function is called with or without arguments and do not compare to uninitialized variables

4.19 undefined

Never use undefined directly for variable judgments;

Use typeof and the string ‘undefined’ to determine variables.

4.20 jshint

Use ‘= = =’, ‘! ==’ instead of ‘==’, ‘! = ‘;

HasOwnProperty = hasOwnProperty;

Do not add methods to the prototype of built-in objects, such as Array, Date;

Do not declare a variable in the inner scope code and then access a variable of the same name in the outer scope.

Do not use variables before declaring them;

Don’t just use constructors in a line of code; assign them to a variable;

Do not declare variables of the same name in the same scope;

Do not put parentheses in unnecessary places, for example: delete(a.b);

Do not use undeclared variables (global variables need to be added to the globals property of the.jshintrc file);

Don’t declare variables and leave them unused;

Don’t assign values where comparisons should be made;

The debugger should not appear in submitted code;

Do not have empty elements in the array;

Do not declare functions inside loops;

Do not use constructors like this, for example: new function () {… }, the new Object;

5.0 Images and third party resources

5.1 Storage Directory

  • Static class resources are placed in the static folder under the project root directory
  • The assets folder is located in the root directory of the project
  • Third-party library class resources are placed in the components folder under the project root directory

5.2 format

Image format is limited to GIF | | PNG | | JPG, as far as possible using PNG format images; Select the minimum image format and image quality while ensuring visual effect to reduce loading time;

5.3 named

The name must be a combination of lowercase letters, digits, and underscores (_), and cannot contain Chinese characters, Spaces, and special characters. The name of the picture is divided into two parts, separated by an underscore, and the first part indicates the category of the picture. The specific rules are as follows:

Banner logo logo on the page position is not fixed and with a link to the small picture name: BTN in a position on the page in a row, the same nature of the link column picture name: Menu decorative picture name: PIC with no link to indicate the title of the picture name: title meaningless only for logo icon name: iconCopy the code

The image naming convention is “image name _on/off”. For example, menu1_on.gif menu1_off. GIF should be easy to understand by other team members.

5.4 other

Use CSS Sprite to concentrate small background images or ICONS to reduce page HTTP requests, but be sure to draw a reference line in the corresponding Sprite PSD source image and save it to the IMG directory.

6.0 JS framework &UI library

6.1 JS universal library

6.1.1 UI

6.1.2 JS Plugin

  • Format day.js, Momentjs
  • Report designer Activereportsjs

6.1 the jquery

6.1.1 the jQuery UI library

6.1.2 jQuery Plugin

  • IE for HTML5 tag support, and browser feature detection: Modernizr & HTML5shiv
  • Customize & unify browser scroll bar styles: jQUERy-Scroll & Lionbars
  • Hover prompt effect text: Bootstrap-Tooltips & tipsy
  • The scroll bar follows the nav effect: bootstrap-scrollSpy
  • Prompt bubbling text: grumble.js
  • Navigation transition Effect: Lavalamp
  • Scrolling on mobile devices: IScroll 4
  • Mac OS Lion-style scrollbars: Lionbars
  • SlideShow: kwicks for jQuery
  • Waterfall flow: isotope
  • Shake effect: jQ Shake
  • LightBox: fancyBox
  • KenDo UI: KenDo UI
  • Textarea adaptive height: elastic
  • Hint area & hint layer: noty
  • Floating topic bubble: jQuery Grumble
  • Rotate progress: jQuery Knob

6.2 Vue Precautions

  • Component name:
  1. Hyphen: All lowercase letters and must contain a hyphen (recommended when using a component directly in the DOM)
Vue.component('my-component-name', { /* ... */ });
Copy the code
  1. Big hump:

Note: When using a non-string template, the props property of camelCase needs to be converted to the corresponding kebab-case (hyphenated).

Vue.com.props ('child', {// Using camelCase props: ['myMessage'], template: vue.com.props ('child', {// Using camelCase props: ['myMessage']], template: '<span>{{myMessage}}</span>'}) (2) <child my-message="hello!" ></child>Copy the code

6.2.1 Vue – UI library

Mobile client:

  • VUX (wechat)
  • Mint UI
  • Muse-ui (Google)
  • Cube UI (Didi)
  • Vant (Thumbs up)

PC:

  • Element UI (Hungry?)
  • iview
  • ant-design-vue
  • vuetify
  • Zent (thumbs up)

6.2.2 Vue Plugin

  • User-defined happy-scroll & Vuescroll
  • Vue-virtual-scrolllist indicates the virtual scroll list
  • Drag to switch position Draggable
  • User-defined dynamic table vxE-table document

6.2.3 Vue

6.3 the React

6.3.1 React – UI library

Mobile client:

  • Ant Design Mobile (Alibaba)
  • Bee Mobile
  • Material-UI (Google responsive)
  • Onsen UI (Angular1, Angular2+, React, Vue)

PC:

  • Ant-design (Alibaba)
  • Material-UI (Google responsive)
  • Semantic-UI-React
  • React-Bootstrap
  • React-Desktop (MacOS & windows)

6.3.2 React the Plugin

6.4 presents

6.4.1 presents – UI library

Mobile client:

  • Ant Design Mobile of Angular
  • Ionic
  • Onsen UI (Angular1, Angular2+, React, Vue)

PC:

  • Ant Design of Angular
  • Angular Material
  • Kendo UI for Angular
  • AgGrid (JS, Angular1, Angular2+, React, Vue)
  • PrimeNG
  • Clarity

6.4.2 presents the Plugin

6.5 Mini programs and public accounts

6.5.1 UI library of small programs and public accounts

  • WeUI WXSS (wechat)

  • IView Appellate P

  • Vant Appellate P

  • Mpvue (wechat, VUE)

  • Wepy (wechat)

  • MinUI (wechat)

  • Wux Appellate P

  • Uni-app (wechat, Alipay, Android, iOS, H5)

  • Taro (wechat, Alipay, H5, Native)

  • More Demo

6.5.2 Plugin for small programs and public accounts

  • The rich text wxParse

6.6 Webpack & NodeJs

6.6.1 Webpack Plugin

  • SVG icon SVG-sprite-loader automatically loads and packs for easy maintenance

6.6.2 npm Plugin

  • Read and export Excel JS-Xlsx (Demo)
  • Read and manipulate cookie js-cookie

7.0 the cache

8.0 HTTP and Interface Requests

9.0 Performance Optimization

9.1 Front-end Optimization

  1. Minimize HTTP requests: Merge multiple CSS files into one.
  2. Compact Javascript and Css code files with Minify.
  3. Putting CSS files in the header of your HTML code prevents the browser from interpreting them once and then using CSS a second time, because users are not interested in CSS running naked.
  4. Avoid CSS expressions. Anything that only IE can use is a bad thing.
  5. Stripping JavaScript and CSS from a page and referencing them in an external file allows you to target them with separate processing strategies, such as compression or caching.
  6. Use instead of @import. In IE, the @import directive is equivalent to writing the link tag at the bottom of the HTML, contrary to the first rule.
  7. Try to put JS at the bottom of the page. When a script is being downloaded, the browser will get stuck and unable to respond to other requests. Therefore, functional JS can be put at the end of the processing.
  8. For mobile devices, a single data object is smaller than 25KB.
  9. Pay attention to the control of Cookie size and pollution, because cookies are local disk files, and the browser will read the corresponding Cookie every time, so it is recommended to remove unnecessary Coockie, make the size of Coockie as small as possible to reduce the impact on user response.

9.2 Image Optimization

  1. Compress the image and use CSS Sprites to optimize the image, which simply means “using CSS background related elements to absolutely locate the background image”, turning multiple HTTP calls into one call and reducing HTTP requests.
  2. Use PNG images whenever possible because PNG has more features and is smaller than GIF.
  3. With a smaller and cacheable favicon.ico, the reason is that without favicon.ico, the server will return a 404, and a large number of 404 will increase the number of server responses compared to a file that can be cached for a long time.

9.3 Server Optimization

  1. Use CDN acceleration, static resources for CDN deployment. (Use front-end CDN to increase the parallel loading speed of web pages, reduce the burden of local servers and save traffic. The default number of concurrent downloads with the same domain name in a browser is 2; HTTP.1.0 specifies 4. In this way, we can use different domain names to speed up the download.
  2. Enable static file compression and compress content using Gzip to reduce broadband requirements and make pages load faster.
  3. Using the GET method for Ajax requests, XMLHttpRequest POST takes two steps, whereas GET takes only one.
  4. Try to use JSON format for data exchange. (Compared to XML serialization, JSON serialized data is generally smaller than XML serialized data.)
  5. The front and back end of the data separation, so that the search service decoupling, in the case of high concurrency more flexible load balancing. (The front-end uses vue. js, AngularJs, etc., with data from any programming language)
  6. Most of the back-end data comes from the cache, which is fast to load and gives users a faster experience. (Commodity details, commodity inventory, etc., can be placed in the cache (Redis cluster), avoid frequent access to the database data, improve the read ability of commodity information)

Summary of front-end performance optimization summary of front-end performance optimization Web front-end optimization to improve the efficiency of the page 14 criteria

9.4 Front-end Performance Testing Tool

Browser plug-in

Google Page Speed: Google Page Speed Test is an open source Firefox/Firebug plug-in. Webmasters and Web developers can use this tool to evaluate the performance of their Web pages and get advice on how to improve them.

YSlow: YSlow analyzes web page performance and suggests improvements based on high-performance web page rules.

PageTest: Plug-in for Internet Explorer, often used to display requests made by the browser when loading content and to provide suggestions for the performance of the incoming page.

Pylot: An open source testing tool for testing web site performance and scalability. It runs HTTP load tests, which are useful for capacity planning, benchmarking, analysis, and system tuning.

Online test site

Pingdom: Tests the load time of all objects on your site (HTML, images, JavaScript, CSS, embedded frames, etc.). You can also check the loading speed of each element of your site and improve items that load slowly. In the test results, you can see the load time report for each element of the site, the size of the element, and the total number of elements. Test address: www.pingdom.com/

GTmetrix: combines YSlow, the most popular Firefox performance component, with Google’s Web speed test tool. Gtmetrix gives you advice on how to improve your website speed, although YSlow’s and Google’s speed tests are specific to Firefox and can be applied to other browsers as well. Test address: gtmetrix.com/

Site-perf: It simulates the browser downloading images, CSS, JS and other files, and in the report you can see which pages of the Site load first and when. This is a very useful performance report that can be used to find elements that need to be improved to improve the loading speed of your site. Test address: gtmetrix.com/

Reference article: 18 commonly used Web site performance testing tools

10.0 Terminal Compatibility

10.1 Resolution Compatibility

10.1.1 Mobile Compatibility

  • Under different DPR, images of different sizes can be loaded. If there is a picture server, parameters can be obtained through the URL, and then picture quality can be controlled, and pictures can also be cropped to different sizes. All we need to do is upload the large image (@2x) and hand over the rest of the small images to the image server. If you don’t have a picture server, prepare multiple pictures of different sizes @1x@2x@3x

  • For different DPR, a 1px wide line should be scaled by 0.5

    Border-bottom: 1px solid # DDD; border-bottom: 1px solid # DDD; -webkit-transform:scaleY(.5); -webkit-transform-origin:0 0; // Option 2: Add the following meta tag, Set viewport(scale 0.5) <meta name="viewport" content="width=640,initial =0.5,maximum-scale=0.5, Minimum - scale = 0.5, user - scalable = no ">Copy the code

10.2 Compatible with Browser Versions

One, identification difference: difference IE6,IE7,IE8,FF.

  1. IE can recognize *; Standard browsers (like FF) do not recognize *;

  2. IE6 can recognize *, but not! important; IE6 prefixes styles with _

  3. IE7 can recognize *, also can recognize! important;

  4. IE8 can recognize \9 for example: background:red \9;

  5. Firefox doesn’t recognize *, but it does! important;

  • Differences between IE6 and Firefox:

background:orange; *background:blue; This means that firefox has an orange background and Internet Explorer has a blue background.

  • Differences between IE6 and IE7:

background:green ! important; background:blue; IE7’s background color is green and IE6’s background color is blue

  • Differences between IE7 and FF:

background:orange; *background:green; Firefox’s background color is orange, while IE7’s is green

  • FF, IE7, IE6

background:orange; *background:green ! important; *background:blue; This means that firefox has an orange background, while IE7 has a green background and IE6 has a blue background.

11.0 Automated Tests