Home Web Front-end JS Tutorial JavaScript code specifications and performance finishing

JavaScript code specifications and performance finishing

Mar 04, 2017 pm 03:11 PM
javascript Code specifications

  1. Performance

There are many things to pay attention to in terms of performance of Js:

  • Avoid global lookup

The most important thing to optimize Js performance is to pay attention to the global search, because the scope search is to first search the local scope, and then go to the upper level scope to search until the global scope is not found, so the performance consumption of the global scope search must be higher than The local scope of this function consumes a lot of money. for example:

function setInnerHtml(){  var pDom=doucument.getElementsByTagName(“p”);  for(var i=0,len=pDom.lemgth;i<len;i++){

    pDom.innerHTML=doucument.getElementByid(“dom”).innerHtml+I;

}

}
Copy after login

This code calls document.getElementByid("dom") in a loop, and the document is only executed once outside the loop, so there is no need to assign the document to a local variable. Instead, assign the value inside the loop to a local variable, so there is no need to re-enter the loop each time. To find the global document object.

function setInnerHtml(){  var domhtml= doucument.getElementByid(“dom”).innerHtml;  var pDom=doucument.getElementsByTagName(“p”);  for(var i=0,len=pDom.lemgth;i<len;i++){

    pDom.innerHTML= domhtml +I;

}

}
Copy after login

The principle is that when the global object is called multiple times, especially in a loop, the global object is finally assigned to the local variable. Of course, the performance difference will not be obvious after dozens of calls, but as a programmer, since Performance-optimized writing should be done as much as possible.

  • Avoid with statements

This statement is rarely used nowadays, so I won’t say more about it.

  • Avoid unnecessary attribute lookups

To put it simply, the variable stores the value. The performance consumption of calling this variable is minimal, while the performance consumption of taking the value of the object's attribute is relatively high. for example:

var query=window.location.href.subtring(window.location.href.indexOf(“?”));
Copy after login

This code has 6 attribute searches that are particularly inefficient. It is best to change it to:

var url=window.loaction.href;var query=url.substring(url.indexOf(“?”));
Copy after login

This optimization improves the efficiency a lot.

  • optimization loop

1) Decrease iteration: Most loops start from 0 and increase the loop. In many cases, it is more efficient to decrease the loop from the maximum value.

2) Simplify the termination conditions: Since the termination conditions will be judged every time it loops, simplifying the termination conditions can also improve loop efficiency.

3) Simplify the loop body: The loop body is the most executed, so the optimization of the loop body must be ensured.

  • Avoid parsing js code string

When parsing js code strings in js code, a parser must be restarted to parse the code, which causes relatively large performance consumption, so try to avoid functions such as eval and function constructing js code words.

String function, when setTimeout passes a string.

  • The native method is faster, so try to use the native method.

  • Switch statement is faster.

  • Bitwise operators are faster.

2. Code specifications

  • Code comments:

1) Functions and methods: Each function or method should contain comments describing the function, input and output of the function.

2) Complex algorithms: Comments should be added to complex algorithms so that people can understand the logical thinking of the algorithm.

3) Hack: Comments should also be added to the compatibility code.

4) Large blocks of code: Multiple lines of code used to complete a single task should be preceded by a comment describing the task.

  • Decoupling HTML/JavaScript

Html is the structure, and js is the behavioral layer. They inherently need to interact. When we write code, we should try to reduce the correlation between html and js. Some methods will make them too tightly coupled, such as: js in the html page Declaring js code in the script tag, binding onclick events in the html tag, and rewriting the html code in js will cause HTML and js to be too tightly coupled.

Html rendering should be kept separate from js as much as possible. When js is used to insert data, try not to insert tags directly. Generally, you can directly include and hide tags in the page, and then wait until the entire page is rendered, and then use js to display the tag. .

将html和js解耦可以在调试过程中节省时间,更加容易确定错误的来源,也减轻维护难度。

  • 解耦css/JavaScript

JavaScript和css也是非常紧密相关的,js经常对页面的样式做动态修改。为了让他们的耦合更松散,可以通过js修改对应的class样式类。

  • 解耦应用逻辑/事件处理程序

在实际开发中我们经常在一个事件函数出来将要处理的所有代码都放在这个事件中,例如:

function handleKeyPress(event){

   event=EventUtil.getTarget(event);   if(event.keyCode===13){var target=EventUtil.getTarget(event);var value=5*parseInt(target.value);if(value>10){

 document.getElementById(“error-msg”).style.display=”block”;

}

}

}
Copy after login

 

这里就是把逻辑处理代码和事件处理代码放到一起,这样会让调试不好调试,维护难度变高,而且要是突然修改要新增加一个事件做同样类似的逻辑处理,那就要复制一份逻辑处理代码到另一个事件函数中。较好的方法是将应用逻辑和事件处理程序分离开。例如:

function validateValue(value){

 value=5*parseInt(value); if(value>10){

 document.getElementById(“error-msg”).style.display=”block”;

}

}function handleKeyPress(event){

  event=EventUtil.getEvent(event);  if(event.keyCode===13){   var target=EventUtil.getTarget(event);

   validateValue(target.value);

}

}
Copy after login

 

这样事件处理和逻辑处理就分离开了,这样做有几个好处,可以让你更容易更改触发特定过程的事件,其次可以在不附加到事件的情况下测试代码,使其更易创建单元测试或是自动化应用流程。

事件和应用逻辑之间的松散耦合的几条原则:

  1. 勿将event对象传给其他方法;只传来着event对象中所需要的数据;

  2. 任何可以在应用层面的动作都应该可以在不执行任何时间处理程序的情况下能正常运行。

  3. 任何时间处理程序都应该处理事件,然后将处理转交给应用逻辑。

  • 避免全局变量

这样会让脚本执行一致和可维护,最多创建一个全局变量。类似jQuery一样,所以方法属性都在$对象当中,避免对全局变量造成过多的污染。

  • 尽量使用常量

数据和使用它的逻辑进行分离要注意一下几点:

  1.  重复值

  2. 用户界面字符串

  3.  url

  4. 任意可能会更改的值

  • 其他优化

  1. 多变量声明时用一条语句逗号隔开声明

  2. 对dom的操作的优化

  3. 对dom进行html代码插入尽量在最后一次添加到dom对象中。

  4. innerHTML的效率要比appendChild的效率高,以为innerHTML会创建一个HTML解析器,然后使用内部的DOM调用来创建DOM结构,而非基于JavaScript的DOM调用,由于内部方法是编译好的而非解释执行,所以执行快的多。

  5. 使用事件委托减少绑定的事件数量。

  6. 尽量少用到返回HTMLCollection语句。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles