Summary of JavaScript knowledge points: how to improve performance and javascript knowledge points

Source: Internet
Author: User

Summary of JavaScript knowledge points: how to improve performance and javascript knowledge points

The performance of JavaScript should not be underestimated. This requires our developers to pay more attention to some details when writing JavaScript programs. This article describes in detail the knowledge points of JavaScript performance optimization, it is definitely a dry product.

First, let's consolidate the basic javascript Syntax:

Basic javascript syntax

Use the var keyword to define variables.

Syntax: var variable name = variable value

Identifier: ①. It is composed of letters, numbers, and underscores. It cannot start with a number. It cannot be a keyword that is case sensitive.

Data Type:

Numeric: number

String: string

Boolean: boolean

Special Data Type: undefined null undefined

Null: null

Reference Type object function

The data type of the detection parameter: typeof () returns the string corresponding to the data type.

Two equal signs = and three equal signs =

=: Equal comparison values are irrelevant to the Data Type

===: Comparison completeness is related to both numerical values and data types.

Boolean environment: if is automatically converted to a Boolean Value

Boolean environment in string: NULL is false, non-null is true

Boolean environment in value number: 0 is false, non-0 is true

Relationship between number and string

①. Join Operations on +

② When an operation is required, convert the string to a numeric value.

Conversion Method 1: Convert string * 1 to numeric type

Conversion Method 2: Number (string) to numeric type

I. js file loading location

In an HTML file, the <script> tag can be added to the

1. if the js file has no special requirements, specify the file to be loaded and compiled before page rendering, then, place the js file in front of the </body> tag (after the content displayed on all pages ), the css file is still placed in the

2. if these js files indicate that they need to be executed first to better display the page content, put a loading animation on the first js or page, it can be used in interesting or cute animation scenarios. This can also better avoid the boredom of users waiting, maybe people are more interested in this loading animation, which can improve the user experience of the project.

Final recommendation: Put the <script> label in front of the </body> label as much as possible to improve user experience.

Ii. Merge js files

In the development of many teams, we may place different functional code blocks in different js files, so that it is more convenient for everyone to write code together during the development process, after all, you only need to find the corresponding folder or file instead of finding a method in a very long file. This will indeed improve the development efficiency of the team and facilitate secondary development and maintenance after the newcomers join. So what about putting this problem into page performance? This is exactly the problem. This book points out that Each HTTP request brings with it additional performance overhead, so downloading one single 100 KB file will be faster than downloading four 25 KB files.

Downloading a kb file is faster than downloading four 25KB files, and separating each file in the development process has great benefits, then the problem of merging will be processed after development. I believe that this operation will not be unfamiliar to everyone. The current front-end tools are so rich that everyone will use compression when they are used to compression ~

The defer and async attributes can also be used to load files. In modern browsers, most of them already support the defer attribute, I am not used to using this amount, and I don't know if there will be any problems. If you are interested, you can google this knowledge point. Here is a simple example.

Currently, most of the frameworks work with lazy loading and on-demand loading.

3. faster data access

For a browser, the deeper the location of an identifier, the slower it is to read and write it (for this reason, the prototype chain is also the same ). It should be easy to understand. A simple analogy is: The farther away the grocery store is from your home, the longer it takes to cook soy sauce... bear child, make soy sauce so long, the food is burned -. -~

If we need to use a variable value multiple times in the current function, we can use a local variable to store it first. The example is as follows:

// Function showLi () {var I = 0; for (; I <document. getElementsByTagName ("li "). length; I ++) {// access the documentconsole at a time. log (I, document. getElementsByTagName ("li") [I]); // three-way access to document };}; // after modification, function showLi () {var li_s = document. getElementsByTagName ("li"); // One-time access to documentvar I = 0; for (; I <li_s.length; I ++) {console. log (I, li_s [I]); // three times to access the local variable li_s };};

Iv. Optimization of DOM operations

As we all know, DOM operations are far more efficient than javascript operations. Although we cannot avoid DOM operations, we can minimize the performance consumption of such operations.

Let's explain this problem through code:

Function innerLi_s () {var I = 0; for (; I <20; I ++) {document. getElementById ("Num "). innerHTML = "A"; // 20 cycles are performed, and two DOM element accesses are performed at A time: the value of innerHTML is read at A time, and the value is written at A time };};

Rewrite the preceding method:

Function innerLi_s () {var content = ""; var I = 0; for (; I <20; I ++) {content + = ""; // here, only js variables are cyclically 20 times}; document. getElementById ("Num "). innerHTML + = content; // here, the value is a DOM operation, and DOM access is performed twice: the value of innerHTML is read at a time, and the value is written at a time };

V. Reduce the deduplication of Dom

Changes to the element layout, content addition, deletion, or browser window size will lead to re-painting. Changes to the font color or background color will lead to re-painting.
For operations similar to the following code, it is said that most modern browsers have been optimized (to be retyped once ):

// Var el = document. getElementById ("div"); el. style. borderLeft = "1px"; // retypeset el once. style. borderRight = "2px"; // re-typeset el once again. style. padding = "5px"; // There is another re-layout // var el = document after modification. getElementById ("div" );el.style.css Text = "border-left: 1px; border-right: 2px; padding: 5px"; // retypeset once

For multiple operations, the following three methods can also reduce the number of re-typographical and re-painting times:

1. the Dom is hidden first, and the operation is then re-displayed twice (temporary display: none)

2.doc ument. createDocumentFragment () creates a document fragment for processing, and appends it to the page for rearranging once.

3. var newDOM = oldDOM. cloneNode (true) create a Dom copy. After the copy is modified, oldDOM. parentNode. replaceChild (newDOM, oldDOM) overwrites the original DOM for two rearrangements.

V. Loop Optimization

This should be something that many people know. It can be simply taken over (it will be described in code + annotations later )~

// Var I = 0; for (; I <arr. lengthli ++) {// you need to obtain the lengthconsole of the array arr for each loop. log (arr [I]);} // var I = 0 after modification; var len = arr. length; // obtain the length for (; I <len; I ++) {console. log (arr [I]);} // orvar I = arr. length; for (; I --) {console. log (arr [I]);}

Vi. Rational Use of Binary

For example, if the modulo operation is performed on 2, the even number of decimal places is 0, the odd number of decimal places is 0, and the result of bitwise AND operation on 1 is 0, and the odd number of decimal places is 1, the result of bitwise AND operation with 1 is 1.

The Code is as follows:

.odd{color:red}.even{color:yellow} <ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li></ul> var i = 0;var lis = document.getElementsByTagName("li");var len = lis.length;for(;i<len;i++){if(i&1){lis[i].className = "even";} else{lis[i].className = "odd";}}; 

Although modern browsers have already done a good job, this animal thinks this is a pursuit of code quality. In addition, a single point or two points won't have much impact on performance, but after being optimized from multiple points, it may be a qualitative leap ~

Articles you may be interested in:
  • Javascript knowledge collection
  • Javascript Excel operation knowledge point
  • JS string connection [Performance Comparison]
  • Performance Comparison and Analysis code for parsing Json strings using JavaScript
  • Performance Comparison of Three array replication methods in javascript
  • High-performance WEB development JS and CSS merging, compression, and Cache Management
  • Test and analyze the performance of json_encode, json_decode, serialize, and unserialize in PHP
  • Summary of important JS knowledge points
  • Summary of basic knowledge points of JavaScript language (mind map)
  • JavaScript improves performance knowledge

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.