Summary of JavaScript front end performance optimization tips

JavaScript language 2020-11-13 05:07:33
summary javascript end performance optimization


In many languages ,JavaScript Has an important place , utilize JavaScript We can do a lot of things , Widely applied .

stay web In the application project , Need a lot of JavaScript Code for , There will be more and more .

But because of JavaScript It's a language for interpretation , And its single thread mechanism , Determined the performance problem is JavaScript Weakness , It's also a developer writing JavaScript A problem to pay attention to .

Because I often meet Web 2.0 Problems of poor application performance , The main reason is JavaScript Poor performance , Causes browser overload . Javascript Performance optimization is by no means a written skill , So how to load and execute correctly JavaScript Code , So as to improve its performance in the browser ? Here is a summary of some tips for optimization .

Regardless of the present JavaScript Is the code embedded or in an external chain file , The download and rendering of the page must stop and wait for the script to finish .JavaScript The longer it takes to execute , The longer the browser waits to respond to user input .

The reason why browsers block when downloading and executing scripts is , The script may change the page or JavaScript The namespace of , They have an impact on the content of subsequent pages . A typical example is the use of :

document.write()

Example :

<html><head>
<title>Source Example</title></head><body>
<p>
<script type="text/javascript">
document.write("Today is " + (new Date()).toDateString()); </script>
</p></body></html>
Front end learning exchange circle :767273102 , It's all about learning the front end from the most basic HTML+CSS+JS【 Cool special effects , game , Plug in encapsulation , Design patterns 】 To mobile HTML5 The learning materials of the project and actual combat have been sorted out , To every front-end partner .2019 Latest technology , Synchronization with enterprise requirements . Friends are learning to communicate in it , Every day, Daniel will regularly explain the front-end technology !

When the browser encounters

therefore , The browser will stop processing the page , Execute first JavaScript Code , Then continue to parse and render the page .

The same thing happens with the use of src Attribute loading JavaScript In the process of , The browser must first take the time to download the code in the chain file , Then parse and execute it . In the process , Page rendering and user interaction are completely blocked .

Do not use with() sentence

This is because with() Statement will add additional variables at the beginning of the scope chain . The extra variable means , When any variable needs to be accessed ,JavaScript Engines need to scan first with() Statement generated variables , And then there's the local variable , Finally, the global variables .

therefore with() Statement has a negative impact on the performance of both local and global variables , In the end, let's optimize JavaScript The performance plan went bankrupt .

Object attributes and array elements are slower than variables

talk about JavaScript The data of , Generally speaking, there is 4 Access mode : The number 、 Variable 、 Object properties and array elements . When considering optimization , The performance of values and variables is similar , And it's significantly faster than object attributes and array elements .

So when you refer to an object attribute or array element multiple times , You can improve performance by defining a variable .( This one is reading 、 It works when writing data ) Although this rule is correct in most cases , however Firefox Some interesting work has been done in optimizing array indexes , Can make its actual performance better than variables .

But considering the performance drawbacks of array elements in other browsers , Or should try to avoid array lookup , Unless you're really focused on Firefox's performance .

Avoid global lookups

In a function, global objects are stored as local variables to reduce global lookups , Because accessing local variables is faster than accessing global variables

function search() {
// When I want to use the current page address and host domain name
alert(window.location.href + window.location.host);
}
// The best way is as follows First save it with a simple variable
function search() {
var location = window.location;
alert(location.href + location.host);
}

avoid with sentence

It's similar to a function ,with Statement will create its own scope , So it will increase the length of the scope chain of the code executed , Due to additional scope chain lookups , stay with The code executed in the statement will certainly be slower than the code executed outside , In can not use with Try not to use with sentence .

with (a.b.c.d) {
property1 = 1;
property2 = 2;
} // Can be replaced with :
var obj = a.b.c.d;
obj.property1 = 1;
obj.property2 = 2;

Number to string

It's better to use ”" + 1 To convert numbers to strings , Although it looks a little ugly , But it's actually the most efficient , In terms of performance :

(“” +) > String() > .toString() > new String()

Through template elements clone, replace createElement

Many people like to be in JavaScript Use in document.write To generate content for a page . In fact, it's less efficient , If you need to insert directly HTML, You can find a container element , For example, specify a div perhaps span, And set up their innerHTML To put your own HTML The code is inserted into the page .

In general, we may use strings to write directly HTML To create nodes , In fact, do this ,1: There is no guarantee that the code is valid ,2: String operation efficiency is low , So it should use document.createElement() Method , And if there are existing template nodes in the document , It should be with cloneNode() Method , Because use createElement() After method , You need to set the attributes of multiple elements , Use cloneNode() You can reduce the number of property settings —— Again, if you need to create many elements , You should prepare a template node first .

var frag = document.createDocumentFragment();
for (var i = 0; i < 1000; i++) {
var el = document.createElement('p');
el.innerHTML = i;
frag.appendChild(el);
} document.body.appendChild(frag);
// Replace with :
var frag = document.createDocumentFragment(); var pEl = document.getElementsByTagName('p')[0];
for (var i = 0; i < 1000; i++) {
var el = pEl.cloneNode(false);
el.innerHTML = i;
frag.appendChild(el);
} document.body.appendChild(frag);

Avoid inefficient script locations

HTML 4 The specification States

Examples of inefficient script locations :

<html><head>
<title>Source Example</title>
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
<script type="text/javascript" src="script3.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css"></head><body>
<p>Hello world!</p></body></html>

However, this conventional approach hides serious performance problems .

In the list 2 In the example , When the browser resolves to

So it's time to JavaScript Before the code is completely executed , The page is blank . The following figure describes the download process of scripts and style files during page loading .

We can find an interesting phenomenon : first JavaScript File start downloading , At the same time, it blocks the download of other files on the page .

Besides , from script1.js Download complete to script2.js There is a delay before downloading , This period of time happens to be script1.js The execution of documents . Each file must wait until the previous file is downloaded and executed before it starts downloading . In the process of downloading these files one by one , What the user sees is a blank page .

from IE 8、Firefox 3.5、Safari 4 and Chrome 2 Allow parallel downloads at first JavaScript file . That's good news , because

Although the script download process does not affect each other , But the page still has to wait for all JavaScript Code download and execution complete before continuing . therefore , Although the latest browsers improve performance by allowing parallel downloads , But the problem is not completely solved , Script blocking is still a problem .

Because the script will block the download of other resources on the page , So it is recommended that all

Recommended code placement examples :

<head>
<title>Source Example</title>
<link rel="stylesheet" type="text/css" href="styles.css"></head><body>
<p>Hello world!</p>
<!-- Example of efficient script positioning -->
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
<script type="text/javascript" src="script3.js"></script></body></html>

This code shows in HTML Place... In the document

This is optimization JavaScript The first rule of : Put the script at the bottom .

Be careful with closures

Although you may not know “ Closure ”, But you may inadvertently use this technology often . Closures are basically considered JavaScript Medium new, When we define an immediate function , We use closures , such as :

document.getElementById('foo').onclick = function(ev) { };

The problem with closures is : According to the definition , There are at least three objects in their scope chain : Closure variables 、 Local and global variables . These extra objects will cause other performance problems . however Nicholas It's not that we should stop eating because of choking , Closures are also very useful for improving code readability , Just don't abuse them ( Especially in the cycle ).

Combine control conditions and control variables in the loop

When it comes to performance , The work that needs to be avoided in the cycle has always been a hot topic , Because the loop will be repeated many times . So if there's a need for performance optimization , It is possible to obtain the most obvious performance improvement by cutting the circulation first .

One way to optimize a loop is to define it , Combine control conditions with control variables , Here's an example of not merging them :

for ( var x = 0; x < 10; x++ ) {
};

When we want to add something to this cycle before , We found that there are several operations that occur in each iteration .JavaScript The engine needs :

#1: Check x Whether there is #2: Check x Is less than 0 <span style="color: #888888;">( There may be a clerical error here )</span>#3: send x increase 1

But if you just iterate over some of the elements , Then you can use while Cycle around to replace the above operation :

var x = 9;do { } while( x-- );

Use XMLHttpRequest(XHR) object

This technique first creates a XHR object , Then download JavaScript file , And then with a dynamic

adopt XHR Loading objects JavaScript Script :

var xhr = new XMLHttpRequest();
xhr.open("get", "script1.js", true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
var script = document.createElement ("script");
script.type = "text/javascript";
script.text = xhr.responseText; document.body.appendChild(script);
}
}
};
xhr.send(null);
Front end learning exchange circle :767273102 , It's all about learning the front end from the most basic HTML+CSS+JS【 Cool special effects , game , Plug in encapsulation , Design patterns 】 To mobile HTML5 The learning materials of the project and actual combat have been sorted out , To every front-end partner .2019 Latest technology , Synchronization with enterprise requirements . Friends are learning to communicate in it , Every day, Daniel will regularly explain the front-end technology !

This code sends a get to the server script1.js Of documents GET request .onreadystatechange Event handler check readyState Is it right? 4, Then check that the HTTP Is the status code valid (2XX To express an effective response ,304 Represents a cached response ).

If a valid response is received , Then create a new one

Doing so actually creates a

The main advantage of this method is , You can download the JavaScript Code . Because the code returned in

Another advantage is , The same code doesn't throw exceptions in any modern browser .

The main limitation of this method is :JavaScript The file must be placed in the same domain as the page , Cannot from CDN download (CDN finger ” Content delivery network (Content Delivery Network)”, So large web pages usually don't use XHR Script injection technology .

Be careful NodeList

Minimize access NodeList The number of times can greatly improve the performance of scripts

var images = document.getElementsByTagName('img'); for (var i = 0, len = images.length;
i < len; i++) {
}

To write JavaScript Be sure to know when to return NodeList object , This minimizes access to them .

1、 It's right getElementsByTagName() Call to

2、 Get the childNodes attribute

3、 Get the attributes attribute

4、 Visited a special collection , Such as document.forms、document.images wait

To understand when using NodeList Object time , Reasonable use will greatly improve the code execution speed

Avoid and null Compare

because JavaScript It's a weak type , So it doesn't do any automatic type checking , So if you see something with null Code to compare , Try the following techniques to replace :

1、 If the value should be a reference type , Use instanceof Operator to check its constructor

2、 If the value should be a basic type , effect typeof Check the type

3、 If you want the object to contain a specific method name , Then use typeof The operator ensures that the named method exists on the object

Respect the ownership of the object

because JavaScript You can modify any object at any time , This allows you to override the default behavior in an unpredictable way , So if you're not responsible for maintaining an object , Its object or its method , Then you don't have to modify it , To be specific, it means :

1、 Don't add properties to instances or prototypes

2、 Don't add methods to instances or prototypes

3、 Don't redefine existing methods

4、 Don't re define the methods that other team members have implemented , Never modify objects that are not owned by you , You can create new functions for objects in the following ways :

01、 Create a new object with the required functionality , And use it to interact with related objects

02、 Create custom types , Inherit types that need to be modified , You can then add extra features for custom types

Circular reference

If the circular reference contains DOM Object or ActiveX object , Then there will be a memory leak .

The result of a memory leak is before the browser shuts down , Even refresh the page , This memory will not be released by the browser .

A simple circular quote :

var el = document.getElementById('MyElement');
var func = function () {
//…
}
el.func = func;
func.element = el;

But it doesn't usually happen . Usually circular references occur for dom Element to add a closure as expendo When .

function init() {
var el = document.getElementById('MyElement');
el.onclick = function () {
//……
}
}
init();

init At the time of execution , The current context is called context. This is the time ,context Refer to the el,el Refer to the function,function Refer to the context. This creates a circular reference .

below 2 There are ways to solve circular references :

1、 empty dom object

function init() {
var el = document.getElementById('MyElement');
el.onclick = function () {
//……
}
}
init();
// Can be replaced with :
function init() {
var el = document.getElementById('MyElement');
el.onclick = function () {
//……
}
el = null;
}
init();

take el empty ,context It doesn't include right dom References to objects , So as to break the cyclic application .

If we need to dom Object returns , You can use the following methods :

function init() {
var el = document.getElementById('MyElement');
el.onclick = function () {
//……
} return el;
}
init();
// Can be replaced with :
function init() {
var el = document.getElementById('MyElement');
el.onclick = function () {
//……
} try {
return el;
} finally {
el = null;
}
}
init();

2、 Construct new context

function init() {
var el = document.getElementById('MyElement');
el.onclick = function () {
//……
}
}
init();
// Can be replaced with :
function elClickHandler() {
//……
} function init() { var el = document.getElementById('MyElement');
el.onclick = elClickHandler;
}
init();

hold function Draw a new one context in , such ,function Of context It doesn't include right el References to , To break the circular reference .

adopt javascript Created dom object , must append Go to the page

IE Next , Script created dom object , without append Go to the page , Refresh the page , This part of memory will not be recycled !

 function create() {
var gc = document.getElementById('GC'); for (var i = 0; i < 5000; i++) {
var el = document.createElement('div');
el.innerHTML = "test";
// The following sentence can be commented out ,
See browser in Task Manager ,
Click the button and refresh the memory changes
gc.appendChild(el);
}
}

String connection

If you want to connect multiple strings , Should use less +=, Such as

s+=a;
s+=b;
s+=c;

Should be written as

s+=a + b + c;

And if it's collecting strings , For example, multiple times for the same string += operation , It's best to use a cache , Use JavaScript Array to collect , Finally using join Method to connect

var buf = [];
for (var i = 0; i < 100; i++) { buf.push(i.toString());
} var all = buf.join("");

Various types of conversion

var myVar = "3.14159",
str = "" + myVar, // to string
i_int = ~ ~myVar, // to integer
f_float = 1 * myVar, // to float
b_bool = !!myVar, /* to boolean - any string with length
and any number except 0 are true */
array = [myVar]; // to array

If you define toString() Method to do type conversion , recommend Explicit call toString() , Because the internal operation is after trying all possibilities , I will try the object toString() Can the method try to translate into String, So it's more efficient to call this method directly .

Multiple type declarations

stay JavaScript All variables in can use a single var Statement to declare , This is the combination of statements , To reduce the execution time of the entire script , Just like the code above , The above code format is quite standard , Make it clear at a glance .

Insert iterator

Such as var name=values[i]; i++; The first two sentences can be written as var name=values[i++].

Use direct quantity

var aTest = new Array(); // Replace with
var aTest = [];
var aTest = new Object; // Replace with
var aTest = {};
var reg = new RegExp(); // Replace with
var reg = /../;
// If you want to create a generic object with some properties , You can also use literal , as follows :
var oFruit = new O;
oFruit.color = "red";
oFruit.name = "apple";
// The previous code can be rewritten in terms of object literals :
var oFruit = { color: "red", name: "apple" };

Avoid double interpretation

If you want to improve code performance , Avoid as much as possible the need to follow JavaScript Interpreted string , That is to say

1、 Use... As little as possible eval function

Use eval Equivalent to calling the interpretation engine again to run the content at run time , It takes a lot of time , And use Eval The security problems brought by it can not be ignored .

2、 Do not use Function Constructors

Don't give setTimeout perhaps setInterval Passing string parameters

var num = 0;
setTimeout('num++', 10);
// Can be replaced with :
var num = 0;
function addNum() {
num++;
}
setTimeout(addNum, 10);

Shorten negative detection

if (oTest != '#ff0000') {
//do something
}
if (oTest != null) {
//do something
}
if (oTest != false) {
//do something
}
// Although all of these are correct , But operating with logical non operators has the same effect :
if (!oTest) {
//do something
}

Release javascript object

stay rich Application , As the number of instanced objects increases , Memory consumption will increase . So you should release references to objects in time , Give Way GC Can reclaim these memory controls .

object :obj = null

Object properties :delete obj.myproperty

Array item: array-based splice Method to release the unused in the array item

Performance considerations

1、 Try to use native methods

2、switch Statement relative if Faster

By way of case Statements are organized in the most likely to least likely order .

3、 Bit operation is faster

When doing numerical operations , Bit operations are faster than any Boolean or arithmetic operations .

4、 Skillfully use || and && Boolean operator

function eventHandler(e) {
if (!e) e = window.event;
}
// Can be replaced with :
function eventHandler(e) {
e = e || window.event;
}
if (myobj) {
doSomething(myobj);
}
// Can be replaced with :
myobj && doSomething(myobj);

What should be paid attention to to to avoid mistakes

1、 A semicolon must be added at the end of each statement

stay if In the sentence , Even if the conditional expression has only one statement, use {} Enclose it , In order to avoid logical errors caused by subsequent statements .

2、 Use + You need to be careful

JavaScript Unlike other programming languages , stay JavaScript in ,’+' In addition to indicating the addition of numerical values , Strings are connected outside , It can also be used as a unary operator , Convert a string to a number . So if it's not used properly , It may be the same as the autoincrement ’++’ Confusion leads to miscalculation .

var valueA = 20;
var valueB = "10";
alert(valueA + valueB); //ouput: 2010
alert(valueA + (+valueB)); //output: 30
alert(valueA + +valueB); //output:30
alert(valueA ++ valueB); //Compile error

3、 Use return The statement needs attention

One with a return value return Don't use () Parentheses to enclose the return value , If you return an expression , Then the expression should correspond to return Keywords on the same line , To avoid compression when , The compression tool automatically adds semicolons, resulting in inconsistent results with the developer .

function F1() {
var valueA = 1;
var valueB = 2;
return valueA + valueB;
}
function F2() {
var valueA = 1;
var valueB = 2;
return
valueA + valueB;
}
alert(F1()); //output: 3
alert(F2()); //ouput: undefined

and = The difference between

To avoid the if and while The conditional part of the statement is assigned , Such as if (a = b), Should be written as if (a == b), But if the comparison is equal , It's best to use the full Rune , That is to use === and ! The operator will be relative to and != It will be better .== and != The operator casts the type .

var valueA = "1";
var valueB = 1;
if (valueA == valueB) {
alert("Equal");
}
else {
alert("Not equal");
}
//output: "Equal"
if (valueA === valueB) {
alert("Equal");
}
else {
alert("Not equal");
}
//output: "Not equal"

Don't use raw grammar

Don't use raw grammar , Write confusing code , Although the computer can recognize and run correctly , But the obscure code is not convenient to maintain later .

Function returns the uniform type

although JavaScript It's a weak type , For functions , Before returning integer data , After that, the return Boolean value can pass both compilation and operation normally , But for the sake of specification and later maintenance, it is easy to understand , It should be ensured that the function should return a uniform data type .

Always check the data type

To check all the data that your method has entered , One is for security , On the other hand, for usability . Users will input wrong data anytime, anywhere . It's not because they're stupid , It's because they're busy , And the way you think is different . use typeof Method to test your function Whether the input received is legal .

When to use single quotes , When to use double quotes

Although in JavaScript among , Both double and single quotes can represent strings , To avoid chaos , We suggest that HTML Use double quotes in , stay JavaScript Use single quotes in , But to be compatible with browsers , In order to resolve without error , Definition JSON Object time , Use double quotes .

Deploy

1、 use JSLint function JavaScript Validators to make sure that there are no syntax errors or that the code has no underlying questions

2、 The recommended compression tool before deployment will JS File compression

3、 File code is used uniformly UTF-8

4、JavaScript The program should try to put .js In the file of , When it needs to be called, it is in HTML China and Israel

JavaScript If the code is not HTML The document is dedicated to , We should try to avoid HTML Write it directly in the document JavaScript Code . Because it will greatly increase HTML File size , It's not good for code compression and cache usage . in addition ,

This will reduce the load due to JavaScript The code affects the load time of other components in the page .

版权声明
本文为[JavaScript language]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple