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

What are the tips for optimizing the performance of JavaScript front-end

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

Share

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

This article mainly explains "what are the JavaScript front-end performance optimization tips". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the JavaScript front-end performance optimization tips?"

Whether the current JavaScript code is embedded or in an outer chain file, the download and rendering of the page must stop and wait for the script to complete. The longer it takes to execute the JavaScript, the longer the browser waits to respond to user input.

The reason why browsers block when downloading and executing scripts is that scripts may change the namespace of the page or JavaScript, which can affect the content of later pages. A typical example is to use it on a page:

[xss_clean] ()

Example:

Source Example

[xss_clean] ("Today is" + (new Date ()) .toDateString ()

When the browser encounters a tag, the current HTML page has no way to know whether JavaScript will report to

The tag adds content, or introduces other elements, or even removes the tag.

Therefore, the browser stops processing the page, executes the JavaScript code, and then continues to parse and render the page.

The same thing happens when loading JavaScript using the src property, where the browser must first take the time to download the code in the outer link file, and then parse and execute it. In the process, page rendering and user interaction are completely blocked.

Do not use the with () statement

This is because the with () statement will add additional variables at the beginning of the scope chain. The extra variables mean that when any variable needs to be accessed, the JavaScript engine needs to scan the variables generated by the with () statement first, then the local variables, and then the global variables.

Therefore, the with () statement has a negative impact on the performance of both local and global variables, which ultimately destroys our plan to optimize JavaScript performance.

Object properties and array elements are slower than variables

When it comes to JavaScript data, there are generally four ways to access it: numeric values, variables, object attributes, and array elements. When considering optimization, the performance of values is similar to that of variables, and the speed is significantly better than that of object attributes and array elements.

So when you refer to an object property or array element multiple times, you can improve performance by defining a variable. (this rule is valid for both reading and writing data.) although this rule is correct in most cases, Firefox has done some interesting work on optimizing array indexes to make it perform better than variables.

But given the performance drawbacks of array elements on other browsers, array lookups should be avoided unless you really focus on the performance of Firefox.

Avoid global lookup

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 alert (_ window.location.href + _ window.location.host);} / / the best way is to first save function search () {var location = _ window.location; alert (location.href + location.host) with a simple variable like this;} avoid with statements

Similar to functions, with statements create their own scope, thus increasing the length of the scope chain of the code executed in it. Due to the additional scope chain lookup, the code executed in the with statement will certainly be slower than the code executed outside, so try not to use the with statement when you can not use the with statement.

With (a.b.c.d) {property1 = 1; property2 = 2;} / / can be replaced by: var obj = a.b.c.d; obj.property1 = 1; obj.property2 = 2; convert numbers to strings

It is best to use "+ 1" to convert numbers into strings, although it looks a little uglier, but in fact this efficiency is the highest, in terms of performance:

("" +) > String () > .toString () > new String () replaces createElement through template element clone

Many people like to use [xss_clean] in JavaScript to generate content for the page. In fact, this is inefficient, and if you need to insert HTML directly, you can find a container element, such as specifying a div or span, and set their innerHTML to insert your own HTML code into the page.

Usually we may use a string to write HTML directly to create a node, in fact, 1: can not guarantee the validity of the code, 2: string operation is inefficient, so we should use the document.createElement () method, and if there is a ready-made template node in the document, we should use the cloneNode () method, because after using the createElement () method, you need to set the properties of the element multiple times. Using cloneNode () reduces the number of attribute 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[xss_clean] = i; frag.appendChild(el); } document.body.appendChild(frag); //替换为: var frag = document.createDocumentFragment(); var pEl = document.getElementsByTagName('p')[0]; for (var i = 0; i < 1000; i++) { var el = pEl.cloneNode(false); el[xss_clean] = i; frag.appendChild(el); } document.body.appendChild(frag);避免低效率的脚本位置 HTML 4 规范指出 标签可以放在 HTML 文档的或中,并允许出现多次。Web 开发人员一般习惯在 中加载外链的 JavaScript,接着用 标签用来加载外链的 CSS 文件或者其他页面信息。 低效率脚本位置示例: Source Example Hello world! 然而这种常规的做法却隐藏着严重的性能问题。 在清单 2 的示例中,当浏览器解析到 标签(第 4 行)时,浏览器会停止解析其后的内容,而优先下载脚本文件,并执行其中的代码,这意味着,其后的 styles.css 样式文件和标签都无法被加载,由于标签无法被加载,那么页面自然就无法渲染了。 因此在该 JavaScript 代码完全执行完之前,页面都是一片空白。下图描述了页面加载过程中脚本和样式文件的下载过程。 我们可以发现一个有趣的现象:第一个 JavaScript 文件开始下载,与此同时阻塞了页面其他文件的下载。 此外,从 script1.js 下载完成到 script2.js 开始下载前存在一个延时,这段时间正好是 script1.js 文件的执行过程。每个文件必须等到前一个文件下载并执行完成才会开始下载。在这些文件逐个下载过程中,用户看到的是一片空白的页面。 从 IE 8、Firefox 3.5、Safari 4 和 Chrome 2 开始都允许并行下载 JavaScript 文件。这是个好消息,因为标签在下载外部资源时不会阻塞其他标签。遗憾的是,JavaScript 下载过程仍然会阻塞其他资源的下载,比如样式文件和图片。 尽管脚本的下载过程不会互相影响,但页面仍然必须等待所有 JavaScript 代码下载并执行完成才能继续。因此,尽管最新的浏览器通过允许并行下载提高了性能,但问题尚未完全解决,脚本阻塞仍然是一个问题。 由于脚本会阻塞页面其他资源的下载,因此推荐将所有标签尽可能放到标签的底部,以尽量减少对整个页面下载的影响。 推荐的代码放置位置示例: Source Example Hello world! 这段代码展示了在 HTML 文档中放置标签的推荐位置。尽管脚本下载会阻塞另一个脚本,但是页面的大部分内容都已经下载完成并显示给了用户,因此页面下载不会显得太慢。 这是优化 JavaScript 的首要规则:将脚本放在底部。 小心使用闭包 虽然你可能还不知道"闭包",但你可能在不经意间经常使用这项技术。闭包基本上被认为是JavaScript中的new,当我们定义一个即时函数的时候,我们就使用了闭包,比如: document.getElementById('foo').onclick = function(ev) { }; 闭包的问题在于:根据定义,在它们的作用域链中至少有三个对象:闭包变量、局部变量和全局变量。这些额外的对象将会导致其他的性能问题。但是Nicholas并不是要我们因噎废食,闭包对于提高代码可读性等方面还是非常有用的,只是不要滥用它们(尤其在循环中)。 在循环时将控制条件和控制变量合并起来 提到性能,在循环中需要避免的工作一直是个热门话题,因为循环会被重复执行很多次。所以如果有性能优化的需求,先对循环开刀有可能会获得最明显的性能提升。 一种优化循环的方法是在定义循环的时候,将控制条件和控制变量合并起来,下面是一个没有将他们合并起来的例子: for ( var x = 0; x < 10; x++ ) { }; 当我们要添加什么东西到这个循环之前,我们发现有几个操作在每次迭代都会出现。JavaScript引擎需要: #1:检查 x 是否存在#2:检查 x 是否小于 0 (这里可能有笔误)#3:使 x 增加 1 然而如果你只是迭代元素中的一些元素,那么你可以使用while循环进行轮转来替代上面这种操作: var x = 9;do { } while( x-- );使用 XMLHttpRequest(XHR)对象 此技术首先创建一个 XHR 对象,然后下载 JavaScript 文件,接着用一个动态元素将 JavaScript 代码注入页面。 通过 XHR 对象加载 JavaScript 脚本: var xhr = new XMLHttpRequest(); xhr.open("get", "script1.js", true); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if (xhr.status >

| xhr.status = 304) {var script = document.createElement ("script"); script.type = "text/javascript"; script.text = xhr.responseText; document.body.appendChild (script);}; xhr.send (null)

This code sends a GET request to the server to get the script1.js file. The onreadystatechange event handler checks whether the readyState is 4, and then checks whether the HTTP status code is valid (2XX represents a valid response, and 304 represents a cached response).

If a valid response is received, create a new element and set its text property to the responseText string received from the server.

Doing so actually creates an element with inline code. Once the new element is added to the document, the code is executed and ready for use.

The main advantage of this approach is that you can download JavaScript code that is not executed immediately. Because the code is returned outside the tag (in other words, it is not constrained by the tag), it does not execute automatically after download, which allows you to postpone execution until everything is ready.

Another advantage is that the same code does not throw exceptions in all modern browsers.

The main limitation of this method is that JavaScript files must be placed in the same domain as the page and cannot be downloaded from CDN (CDN refers to "content delivery Network (Content Delivery Network)", so large web pages usually do not use XHR script injection technology.

Pay attention to NodeList

Minimizing the number of visits to NodeList can greatly improve script performance

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

When writing JavaScript, be sure to know when to return NodeList objects so that access to them is minimized.

1. Call getElementsByTagName ()

2. Get the childNodes attribute of the element

3. Get the attributes attribute of the element

4. Access special collections, such as document.forms, document.images, etc.

To understand that when using NodeList objects, reasonable use will greatly improve the speed of code execution

Avoid comparing with null

Because JavaScript is weakly typed, it does not do any automatic type checking, so if you see code that is compared to null, try replacing it with the following techniques:

1. If the value should be a reference type, check its constructor using the instanceof operator

2. If the value should be a basic type, use typeof to check its type

3. If you want the object to contain a specific method name, use the typeof operator to ensure that the method that specifies the name exists on the object

Respect the ownership of the object

Because JavaScript can modify any object at any time, so that the default behavior can be overridden in an unpredictable way, so if you are not responsible for maintaining an object, its object, or its methods, then you should not modify it, specifically:

1. Do not add properties to the instance or prototype

2. Do not add methods to instances or prototypes

3. Do not redefine existing methods

4. Do not repeatedly define methods that other team members have implemented, and never modify objects that are not owned by you. You can create new functions for objects in the following ways:

Create a new object that contains the required functions and use it to interact with related objects

Create a custom type, inherit the type that needs to be modified, and then add additional functionality to the custom type

Circular reference

If the circular reference contains a DOM object or an ActiveX object, then a memory leak occurs.

The consequence of a memory leak is that this part of the memory will not be released by the browser until the browser is closed, even if the page is refreshed.

Simple circular references:

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

But that doesn't usually happen. A circular reference usually occurs when a closure is added as an expendo for a dom element.

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

When init is executed, the current context is called context. At this point, context references el,el, function,function and context. A circular reference is formed at this time.

There are two ways to solve circular references:

1. Leave the dom object empty

Function init () {var el = document.getElementById ('MyElement'); el.onclick = function () {/ /. }} init (); / / can be replaced by: function init () {var el = document.getElementById ('MyElement'); el.onclick = function () {/ /. } el = null;} init ()

Leave the el empty and the context does not contain a reference to the dom object, thus breaking the application of the loop.

If we need to return the dom object, we can use the following method:

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

2. Construct a new context

Function init () {var el = document.getElementById ('MyElement'); el.onclick = function () {/ /. }} init (); / / can be replaced by: function elClickHandler () {/ /. } function init () {var el = document.getElementById ('MyElement'); el.onclick = elClickHandler;} init ()

Pull the function into the new context so that the context of the function does not contain a reference to the el, thus breaking the circular reference.

Dom objects created through javascript must be append into the page

Under IE, if the dom object created by the script does not have append to the page, refresh the page, this part of memory will not be reclaimed!

Function create () {var gc = document.getElementById ('GC'); for (var I = 0; I < 5000; iSue +) {var el = document.createElement (' div'); el [XSS _ clean] = "test"; / / the following sentence can be commented out, look at the browser in the task manager, click the button and refresh the memory change gc.appendChild (el);}} string concatenation

If you want to concatenate multiple strings, you should use + = less, such as

Swarming; swarming; swarming

It should be written as

Swarms: a + b + c

If you are collecting strings, such as performing + = operations on the same string multiple times, it is best to use a cache, use the JavaScript array to collect, and finally use the join method to concatenate

Var buf = []; for (var I = 0; I < 100; iTunes +) {buf.push (i.toString ());} var all = buf.join ("") Conversion of various types 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 the toString () method is defined for type conversion, it is recommended to explicitly call toString (), because the internal operation will try whether the object's toString () method can be converted to String after trying all the possibilities, so it is more efficient to call this method directly.

Multiple type declarations

In JavaScript, all variables can be declared using a single var statement, which is a combined statement to reduce the execution time of the entire script, just like the above code, the format of the above code is quite standard and easy to understand.

Insert iterator

For example, the first two statements can be written as var name=values [I]; iSuppli +].

Use the 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 quantities as follows: var oFruit = new O; oFruit.color = "red"; oFruit.name = "apple" / / the previous code can be rewritten as follows: var oFruit = {color: "red", name: "apple"}; avoid double interpretation

If you want to improve code performance, try to avoid strings that need to be interpreted according to JavaScript, that is,

1. Use the eval function as little as possible

Using eval is equivalent to calling the interpretation engine to run the content again at run time, which takes a lot of time, and the security problems caused by using Eval can not be ignored.

2. Do not use the Function constructor

Do not pass string parameters to setTimeout or setInterval

Var num = 0; setTimeout ('num++', 10); / / can be replaced by: 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 these are correct, using logical non-operators has the same effect: if (! oTest) {/ / do something} releases the javascript object

In rich applications, with the increase in the number of instantiated objects, memory consumption will become larger and larger. So you should release references to objects in time so that GC can recycle these memory controls.

Object: obj = null

Object property: delete obj.myproperty

Array item: use the array's splice method to release unused item in the array

Performance considerations

1. Use native methods as much as possible

2. Switch statement is faster than if.

By organizing the case statements in the most likely to the most unlikely order.

3. Bit operation is fast.

When performing numeric operations, bit operations are faster than any Boolean or arithmetic operations.

4. Skillful use of | and & & Boolean operators

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); attention should be paid to avoid errors

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

In if statements, even if the conditional expression has only one statement, enclose it with {} to avoid logic errors if you add the statement later.

2. Be careful when using the + sign

JavaScript is different from other programming languages in that in JavaScript, in addition to adding numeric values and concatenating strings, they can also be used as unary operators to convert strings into numbers. Therefore, if it is not used properly, it may be confused with the self-increment'+ 'and cause calculation errors.

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. Attention should be paid to the use of the declare sentence

A return statement with a return value should not enclose the return value with () parentheses. If an expression is returned, the expression should be on the same line as the return keyword, so as to avoid that the compression tool automatically adds a semicolon and returns 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 = =

Avoid assigning values in the conditional parts of if and while statements, such as if (a = b), which should be written as if (a = = b), but when comparing equality, it is better to use the congruent operator, that is, the = = and! = operators are better than the = and! = operators. The = = and! = operators cast 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" do not use biased syntax

Do not use biased syntax, write confusing code, although the computer can correctly identify and run, but obscure code is not easy to maintain later.

Function returns a uniform type

Although JavaScript is weakly typed, for a function, the integer data is returned first, and the Boolean value is returned later, but for specification and later maintenance, it is easy to understand that the function should return a uniform data type.

Always check the data type

Check all the data entered by your method for security on the one hand and usability on the other. Users enter the wrong data anytime, anywhere. This is not because they are stupid, but because they are busy and think differently from you. Use the typeof method to check whether the input accepted by your function is valid.

When to use single quotes and when to use double quotes

Although in JavaScript, both double quotes and single quotes can represent strings, in order to avoid confusion, we recommend using double quotes in HTML and single quotes in JavaScript, but in order to be compatible with various browsers and to parse without errors, it is best to use double quotes when defining JSON objects.

Deployment

1. Run the JavaScript validator with JSLint to make sure there are no syntax errors or no potential questions in the code

2. It is recommended to use a compression tool to compress JS files before deployment.

3. UTF-8 is used for uniform file coding.

4. JavaScript programs should be placed in .js files as far as possible, and should be included in HTML when needed.

If the JavaScript code is not specific to the HTML file, you should try to avoid writing JavaScript code directly in the HTML file. Because this will greatly increase the size of the HTML file, it is not conducive to code compression and cache use. In addition, the label should be placed at the back of the file as far as possible, preferably in front of the label.

Thank you for reading, the above is the content of "what are the JavaScript front-end performance optimization tips". After the study of this article, I believe you have a deeper understanding of what the JavaScript front-end performance optimization tips have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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