search
HomeWeb Front-endJS TutorialHigh-performance JAVASCRIPT_javascript tips you don't know

This article will share some best practices for efficient JavaScript to improve everyone’s understanding of the underlying and implementation principles of JS.

Data Storage

A classic problem in computer science is to obtain the best read and write performance by changing the location of data storage. In JavaScript, the location of data storage will have a significant impact on code performance. – If you can use {} to create an object, don’t use new Object. If you can use [] to create an array, don’t use new Array. The access speed of literals in JS is higher than that of objects. – The deeper a variable is in the scope chain, the longer it takes to access it. For this kind of variable, you can save it using local variables through caching to reduce the number of accesses to the scope chain - there is not much difference between using dot notation (object.name) and operator (object[name]), only Safari will There is a difference, click is always faster

Loop

Common loops in JS include the following types:

for(var i = 0; i < 10; i++) { // do something} 
for(var prop in object) { // for loop object}  
[1,2].forEach(function(value, index, array) { // 基于函数的循环})

There is no doubt that the first method is native, has the lowest performance consumption and is the fastest. The second method of for-in will generate more overhead (local variables) for each iteration, and its speed is only 1/7 of the first method. The third method obviously provides a more convenient loop method, but its speed Only 1/8 of the normal cycle. Therefore, you can choose the appropriate recycling method according to your project situation.

Event Delegate

Imagine adding an event to each A tag on the page. Will we add an onClick to each tag? When there are a large number of elements in the page that need to be bound to the same event handler, this situation may affect performance. Each event bound increases the load on the page or during runtime. For a rich front-end application, too many bindings will occupy too much memory on pages with heavy interaction. A simple and elegant way is event delegation. It is an event-based workflow: capture layer by layer, reach the target, and bubble layer by layer. Since there is a bubbling mechanism for events, we can handle events from all child elements by binding events to the outer layer.

document.getElementById('content').onclick = function(e) { 
  e = e || window.event;  
  var target = e.target || e.srcElement;  //如果不是 A标签,我就退出  
  if(target.nodeNmae !=== 'A') { return }  //打印A的链接地址  
  console.log(target.href) }

Redraw and rearrange

After the browser downloads HTMl, CSS, and JS, it will generate two trees: DOM tree and rendering tree. When the geometric properties of the Dom change, such as the width, height, color, and position of the Dom, the browser needs to recalculate the geometric properties of the element and rebuild the rendering tree. This process is called redrawing and rearrangement.

bodystyle = document.body.style; 
bodystyle.color = red; 
bodystyle.height = 1000px; 
bodystyke.width = 100%;

Modifying the three properties in the above method will cause the browser to reflow and redraw three times. In some cases, reducing this reflow can improve browser rendering performance. The recommended method is as follows, only perform one operation and complete three steps:

bodystyle = document.body.style; 
bodystyle.cssText 'color:red;height:1000px;width:100%';

JavaScript loading

IE8, Firefox3.5, and Chrome2 all allow JavaScript files to be downloaded. So <script> will not block other tags from downloading. Unfortunately, the JS download process will still block the download of other resources, such as pictures. Although the latest browsers have improved performance by allowing parallel downloads, script blocking remains a problem. Therefore, it is recommended to place all <script> tags at the bottom of the <body> tag to minimize the impact on the rendering of the entire page and prevent users from seeing a blank </script>

High performance deployment of JS files

Now that everyone knows that multiple <script> tags will affect the page rendering speed, it is not difficult to understand that "reducing the HTTP required for page rendering" is a classic rule for improving website speed. Therefore, merging all JS files in a production environment will reduce the number of requests and thus speed up page rendering. In addition to merging JS files, we can also compress JS files. Compression refers to stripping away parts of a file that are not relevant to running the file. Stripped content includes whitespace characters, and comments. The modification process can usually reduce the file size by half. There are also some compression tools that will reduce the length of local variables, such as: </script>

var myName = "foo" + "bar"; 
//压缩后变成 
var a = "foobar";

Caching JS files

Caching HTTP components can greatly improve the user experience of return visits to the website. The web server uses the "Expires HTTP response header" to tell the client how long a resource should be cached. Of course, caching has its own drawbacks: when your application is upgraded, you need to ensure that users download the latest static content. This problem can be solved by changing the file name of the static resources. You may see the browser referencing jsapplication-20151123201212.js in the production environment. This saves the new JS file as a timestamp to solve the problem of cache not being updated.

Summary

Of course, efficient JS does not only have these areas that can be improved. If we can reduce some performance losses, we can use JavaScript to develop more efficiently.

Everything you didn’t know about high-performance JAVASCRIPT, now you know it!

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool