Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to improve the performance Optimization of web Front end

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to improve the performance optimization of the web front-end, I believe that many inexperienced people do not know what to do. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Front-end performance optimization is a continuous pursuit of the process, although the previous article explained some performance optimization, but there is still a long way to go about performance optimization, a lot of things are not mentioned.

Operator

1. When using operators, try to use operation symbols such as + =,-=, * =,\ =, instead of assigning values directly.

2. Bit operation.

When performing a mathematical operation, the bit operation is faster than any Boolean operation or arithmetic operation, such as modulus, logic and logic or you can also consider replacing it with a bit operation.

Some students asked, what are the common js bit operators? Common bit operators are "~, &, |, ^, > >" and so on.

With regard to the application of bit operations, I also mentioned in the previous article, what is the usage and function of the js operator single vertical bar "|"? As well as javascript practical skills, js small knowledge you can go to see.

Conventional optimization

1. Switch statement.

If you have a series of complex if-else statements, you can convert them into a single switch statement to get faster code, and you can further optimize the case statements by organizing them in the most likely to the most unlikely order.

For example:

Function getCategory (age) {var category = ""; switch (true) {case isNaN (age): category = "not an age"; break; case (age > = 50): category = "Old"; break; case (age .toString () > new String ().

String () is an internal function, so it is very fast. .toString () queries the functions in the prototype, so it is slightly slower. New String () is the slowest.

2. Convert floating-point numbers to integers.

Incorrect use of parseInt ().

ParseInt () is used to convert strings to numbers, not between floating-point numbers and integers.

You should use Math.floor () or Math.round ().

Math is an internal object, so Math.floor () doesn't actually have much time to query methods and calls, and it's the fastest.

Cycle

1. Define variables to avoid getting each time

/ * * inefficient * * / var divs = document.getElementsByTagName ("div"); for (var I = 0; I

< divs.length; i++){ ... } /**效率高,适用于获取DOM集合,如果纯数组则两种情况区别不大**/ var divs = document.getElementsByTagName("div"); for(var i = 0, len = divs.length; i < len; i++){ ... } 2、避免在循环中使用try-catch。 try-catch-finally语句在catch语句被执行的过程中会动态构造变量插入到当前域中,对性能有一定影响。 如果需要异常处理机制,可以将其放在循环外层使用。 循环外使用try-catch try { for ( var i = 0; i < 200; i++) {}} catch (e){} 3、避免遍历大量元素,尽量缩小遍历范围。 作用域链和闭包优化 1、作用域。 作用域(scope)是JAVASCRIPT编程中一个重要的运行机制,在JAVASCRIPT同步和异步编程以及JAVASCRIPT内存管理中起着至关重要的作用。 在JAVASCRIPT中,能形成作用域的有如下几点。 函数的调用with语句with会创建自已的作用域,因此会增加其中执行代码的作用域的长度。全局作用域。 以下代码为例: var foo = function() { var local = {};};foo();console.log(local); //=>

Undefinedvar bar = function () {local = {};}; bar (); console.log (local); / / = > {} / * * here we define the foo () function and bar () function, both of which are intended to define a variable named local. In the foo () function, we use the varstatement to declare and define a local variable, and because the body of the function forms a scope, this variable is defined to that scope. And the body of the foo () function does not do any scope extension, so after the function is executed, the local variable is destroyed. The variable is not accessible in the outer scope. In the bar () function, the local variable is not declared with the varstatement. Instead, the local is defined as a global variable. So the outer scope can access this variable. * * / local = {}; / / the definition here is equivalent to global.local = {}

2. Domain chain

In JAVASCRIPT programming, you will encounter the scenario of multi-layer function nesting, which is the typical representation of scope chain.

Function foo () {var val = 'hello'; function bar () {function baz () {global.val =' world;'}; baz (); console.log (val); / / = > hello}; bar ();}; foo (); / * * in `JAVASCRIPT`, the lookup of variable identifiers starts from the current scope to the global scope. Therefore, the access to variables in the `JAVASCRIPT` code can only be done outward, not vice versa. The execution of the baz () function defines a global variable val in the global scope. In the bar () function, the val identifier is accessed according to the inside-out search principle: if it is not found in the scope of the bar function, it goes to the upper level, that is, the scope of the foo () function. However, the key to confusion is here: if the identifier access finds a matching variable in the scope of the foo () function, it will not continue to look outside, so the global variable val defined in the baz () function does not have an impact on this variable access. * * /

3. Reduce the number of searches on the scope chain

/ * * inefficient * * / for (var I = 0; I

< 10000; i++){ var but1 = document.getElementById("but1");}/**效率高**//**避免全局查找**/var doc = document;for(var i = 0; i < 10000; i++){ var but1 = doc.getElementById("but1");}/**上面代码中,第二种情况是先把全局对象的变量放到函数里面先保存下来,然后直接访问这个变量,而第一种情况是每次都遍历作用域链,直到全局环境,我们看到第二种情况实际上只遍历了一次,而第一种情况却是每次都遍历了,而且这种差别在多级作用域链和多个全局变量的情况下还会表现的非常明显。在作用域链查找的次数是`O(n)`。通过创建一个指向`document`的局部变量,就可以通过限制一次全局查找来改进这个函数的性能。**/ 4、闭包 JAVASCRIPT中的标识符查找遵循从内到外的原则。 function foo() { var local = 'Hello'; return function() { return local; };}var bar = foo();console.log(bar()); //=>

Hello/** the technique shown here to allow the outer scope to access the inner scope is Closure. Thanks to the application of higher-order function, the scope of foo () function is extended. The foo () function returns an anonymous function that exists in the scope of the foo () function, so you can access the local variable in the scope of the foo () function and save its reference. Because this function returns the local variable directly, the bar () function can be executed directly in the outer scope to get the local variable. * * /

Closure is an advanced feature of JAVASCRIPT, because the function with internal variable references is taken out of the function, so the variables in the scope are not necessarily destroyed after the function is executed, until all references to the internal variables are de-referenced. Therefore, the application of closures can easily cause memory not to be freed.

Good closure management.

When closures must be used for loop event bindings, private properties, callbacks with parameters, and so on, be careful with the details.

To loop bind events, let's assume a scenario where there are six buttons corresponding to six events, and when the user clicks the button, the corresponding event is output at the specified place. Var btns = document.querySelectorAll ('.btn'); / 6 elementsvar output = document.querySelector ('# output'); var events = [1, 2, 3, 4, 5, 6]; / / Case 1for (var I = 0; I < btns.length; iTunes +) {btns [I] .onclick = function (evt) {output.innerText + = 'Clicked' + events [I];} } / * * the first solution here is obviously a typical circular binding event error. I won't go into details here, but you can refer to my answer to a netizen for details. The difference between the second and third scenarios lies in the parameters passed in by the closure. * * / Case 2for (var I = 0; I < btns.length; iTunes +) {btns [I] .onclick = (function (index) {return function (evt) {output.innerText + = 'Clicked' + events [index];};}) (I);} / * * the parameter passed in in the second scenario is the current loop subscript, which is passed directly to the corresponding event object. In fact, the latter is more suitable for the application of a large amount of data, because in the functional programming of JavaScript, the parameter passed in when the function is called is a basic type object, then the formal parameter obtained in the body of the function will be a copied value, so that the value is defined as a local variable in the scope of the function body, and the events variable can be dereferenced manually after the event binding is completed. To reduce memory footprint in the outer scope. And when an element is deleted, the corresponding event listener functions, event objects, and closure functions are destroyed and reclaimed. * * / / Case 3for (var I = 0; I < btns.length; iTunes +) {btns.onclick = (function (event) {return function (evt) {output.innerText + = 'Clicked' + event;};}) (Clicked [I]);}

Avoid closure traps

Closures are a powerful tool, but they are also one of the main causes of performance problems. Improper use of closures can lead to memory leaks.

The performance of closures is not as good as using internal methods, let alone reusing external methods.

Because the DOM node of IE 9 browser is implemented as a COM object, the memory of COM is managed by reference counting, and the difficulty of reference counting is circular reference. once DOM references a closure (such as event handler), and the upper elements of the closure refer to the DOM, it will cause circular references and lead to memory leaks.

Make good use of function

Use an anonymous function to wrap around the outermost layer of the code.

; (function () {/ / main business code}) ()

Some are even more advanced:

; (function (win, doc, $, undefined) {/ / main business code}) (window, document, jQuery)

Even front-end modular loading solutions such as RequireJS, SeaJS, and OzJS take a similar form:

/ * * RequireJS**/define (['jquery'], function ($) {/ / main business code}); / * * SeaJS**/define (' module', ['dep',' underscore'], function ($, _) {/ / main business code})

Make good use of callback function

In the process of making a web page, where we use more, we usually encapsulate it into a function. When encapsulating functions, make good use of callback functions.

Examples are as follows:

Function getData (callBack) {$.ajax ({url: ", data: {}, dataType:" json ", type:" get ", success:function (data) {callBack (null,data)}})})}

We can call as follows:

GetData (function (error,data) {console.log (data)})

The fastest way to insert elements in an array

Inserting elements into an array is a common thing. You can use push to insert elements at the end of the array, unshift to insert elements at the head of the array, or splice to insert elements in the middle of the array. But these known methods do not mean that there are no more efficient ones.

Insert elements at the tail

We have two arrays.

Var arr = [1, var arr2, 2, 3, 4, 5];

The tests are as follows:

Arr [arr.length] = 6; / / fastest arr.push (6); / / slow 34.66%arr2 = arr.concat ([6]); / / slow 85.79%

Insert element before

Var arr = [1, 2, 3, 4, 5]; arr.unshift (0); [0] .concat (arr)

Found:

[0] .concat (arr); / / Fast arr.unshift (0); / / slow 64.70%

Add elements to the middle of the array

Using splice, you can simply add elements to the middle of an array, which is the most efficient way.

Var items = ['one',' two', 'three',' four']; items.splice (items.length / 2,0, 'hello'); after reading the above, have you mastered how to improve the performance optimization of the web front end? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report