Table of Contents
Data Storage
Loop
Event Delegation
Redrawing and Rearranging
JavaScript loading
High-performance deployment of JS files
Caching JS files
Summary
Home Web Front-end JS Tutorial What you must know about high-performance Javascript

What you must know about high-performance Javascript

Jun 23, 2020 pm 12:51 PM

What you must know about high-performance Javascript

Everyone must know that JavaScript is a full-stack development language. JS can be seen in browsers, mobile phones, and servers. 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 an impact on code performance. Tremendous influence. – 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, the point is always faster

Loop

The 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) { // 基于函数的循环})
Copy after login

There is no doubt that the first method is native and has better performance The one with the lowest consumption is also 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 Delegation

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 binding of an event 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(&#39;content&#39;).onclick = function(e) { 
    e = e || window.event;    
    var target = e.target || e.srcElement;    //如果不是 A标签,我就退出   
    if(target.nodeNmae !=== &#39;A&#39;) { return }   //打印A的链接地址    
    console.log(target.href) }
Copy after login

Redrawing and Rearranging

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%;
Copy after login

When the three attributes are modified in the above method, the browser will reflow and redraw three times. In some cases, reducing this rearrangement can improve the browser rendering performance. The recommended method is as follows, only perform one operation and complete three steps:

bodystyle = document.body.style; 
bodystyle.cssText &#39;color:red;height:1000px;width:100%&#39;;
Copy after login

JavaScript loading

IE8, Firefox3.5, and Chrome2 all allow mandatory downloading of JavaScript files. So <script> will not block the downloading of other tags. Unfortunately, the JS download process will still block the download of other resources, such as images. 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 avoid users seeing a blank space

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 "reduce the amount of time required for page rendering "HTTP" 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:

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

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.

Recommended tutorial: "javascript basic tutorial"

The above is the detailed content of What you must know about high-performance Javascript. For more information, please follow other related articles on the PHP Chinese website!

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles