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 code optimization recommendations for fourteen JavaScript?

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I would like to talk to you about 14 JavaScript code optimization suggestions, many people may not understand, in order to let you better understand, the editor summed up the following content, I hope you can get something according to this article.

JavaScript has become one of the most popular programming languages. According to W3Tech, almost 96% of the world's websites use it. The most important thing you need to know about the website is that you cannot control the hardware specifications of the users who visit your site. End users who visit your site may use high-end or low-end devices with good or poor Internet connections. This means that you have to make sure that your site is as optimized as possible and that you can meet the requirements of any user.

Here are some tips to help you better optimize your JavaScript code and improve performance.

1. Remove unused code and features

The more code the program contains, the more data it passes to the client. Browsers also need more time to parse and compile the code.

Sometimes, the code may contain completely unused features, and it is best to keep the extra code in the development environment and not to leave it in the production environment, because useless code may increase the burden on the client browser.

Often ask yourself if that function, feature, or code is required.

You can delete useless code manually, or you can delete it for you with the tool Uglify or Closure Compiler developed by Google. You can even use a technique called tree shaking to remove unused code from the program. For example, the packaging tool Webpack provides it. You can learn more about tree shaking here. Also, if you want to delete unused npm packages, you can type the command npm prune.

two。 Cache as much as possible

Caching improves the speed and performance of the site by reducing wait time and network requests, thus reducing the time it takes to display resources. You can do this with the help of caching API or HTTP caching. You may wonder what happens when the content changes. The above caching mechanism can process and regenerate the cache when certain conditions are met, such as publishing new content.

3. Avoid memory leaks

As a high-level language, JS is responsible for several low-level management, such as memory management. Garbage collection is a common process for most programming languages. In popular terms, garbage collection is simply collecting and releasing memory that has been allocated to an object but is not currently used by any part of the program. In programming languages like C, developers must use the malloc () and dealloc () functions to handle memory allocation and recycling.

Although garbage collection is performed automatically by JavaScript, in some cases it may not be perfect. In JavaScript ES6, Map and Set are introduced along with their "weaker" sibling elements. "weaker" corresponds to WeakMap and WeakSet and holds a "weak reference" of each key object. They allow garbage collection of unreferenced values, thereby preventing memory leaks. Learn more about WeakMaps.

4. Jump out of the cycle Try to Break Out of Loops Early as soon as possible

Executing a loop is sure to consume a lot of valuable time in a loop with a large amount of code, which is why the loop should be broken as soon as possible. You can use the break keyword and the continue keyword to jump out of the loop. It is the developer's responsibility to write the most effective code.

In the following example, if you don't use break in a loop, your code will run the loop 1000000000 times, which is obviously overloaded.

Let arr = new Array (1000000000). Fill ('- -'); arr = 'found'; for (let I = 0; I

< arr.length; i++) { if (arr[i] === 'found') { console.log("Found"); break; } } 在下面的例子中,当不满足条件时如果你不使用 continue,那么将执行函数 1000000000 次。而我们只处理了位于偶数位置的数组元素,就将循环执行减少了近一半。 let arr = new Array(1000000000).fill('----'); arr[970] = 'found'; for (let i = 0; i < arr.length; i++) { if(i%2!=0){ continue; }; process(arr[i]); } 5. 最小化变量的计算次数 要减少计算变量的次数,可以使用闭包。JavaScript 中的闭包允许你从内部函数访问外部函数作用域。每次创建一个函数时都会创建闭包——但不调用。内部函数可以访问外部作用域的变量,即使外部函数已经调用结束。 让我们看两个例子,看看这是怎么回事。这些例子的灵感来自 Bret 的博客。 function findCustomerCity(name) { const texasCustomers = ['John', 'Ludwig', 'Kate']; const californiaCustomers = ['Wade', 'Lucie','Kylie']; return texasCustomers.includes(name) ? 'Texas' : californiaCustomers.includes(name) ? 'California' : 'Unknown'; }; 如果我们多次调用上述函数,每次都会创建一个新对象。对于每个调用,不会将内存重新分配给变量 texasCustometrs 和 californiaCustomers。 通过使用带有闭包的解决方案,我们只能实例化变量一次。让我们看看下面的例子。 function findCustomerCity() { const texasCustomers = ['John', 'Ludwig', 'Kate']; const californiaCustomers = ['Wade', 'Lucie','Kylie']; return name =>

TexasCustomers.includes (name)? 'Texas': californiaCustomers.includes (name)? 'California':' Unknown';}; let cityOfCustomer = findCustomerCity (); cityOfCustomer ('John'); / / Texas cityOfCustomer (' Wade'); / / California cityOfCustomer ('Max'); / / Unknown

In the above example, with the help of the closure, the internal function returned to the variable cityOfCustomer can access the constant of the external function findCustomerCity (). And when you call an internal function and pass the parameter name, you don't need to instantiate these constants again.

6. Minimize access to DOM

Access to DOM is slower than other JavaScript statements. If you want to manipulate DOM, which triggers a redrawing of the layout, the operation will become quite slow.

To reduce the number of times you access the DOM element, visit it once and use it as a local variable. When the requirement is complete, be sure to delete the value of the variable by setting it to null. This will prevent memory leaks because it allows garbage collection.

7. Compressed file

By using compression methods such as Gzip, you can reduce the size of the JavaScript file. These smaller files will improve the performance of the site because browsers only need to download smaller resources.

These compressions can reduce file size by up to 80%. Learn more about compression: https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer#text_compression_with_gzip here.

8. Shrink your final code

Some people think that shrinking is the same as compressing. But on the contrary, they are different. In compression, a special algorithm is used to change the size of the output file. However, in zooming out, you need to remove comments and extra spaces from the JavaScript file. This process can be done with the help of many tools and software packages found online. Shrinking has become a major part of the standard practice of page optimization and front-end optimization.

Shrinking can reduce your file size by up to 60%.

9. Use throttling throttle and anti-shake debounce

By using these two techniques, we can strictly enforce the number of times the code needs to handle events.

Throttling is the maximum number of times a function is called within a specified period of time. For example, "the onkeyup event function is executed at most every 1000 milliseconds." This means that if you enter 20 keys per second, the event will be triggered only once per second. This reduces the loading of the code.

Anti-shaking, on the other hand, refers to the shortest interval at which a function is triggered again after it was last triggered. In other words, "execute the function only after 600 milliseconds without calling it". This will mean that your function will not be called until 600 milliseconds later, when the same function is executed for the last time. To learn more about throttling and anti-shaking, here's a quick read.

You can implement your own anti-shake and throttling functions, or you can import them from libraries like Lodash and Underscore.

10. Avoid using the delete keyword

The delete keyword is used to remove properties from an object. There has been some controversy about the performance of this delete keyword. You can view them here and [here] (https://stackoverflow.com/questions/43594092/slow-delete-of-object- propertieses-in-js-in-v8/44008788). This problem is expected to be solved in future updates.

As an alternative, you can simply to set the unwanted property as undefined. Alternatively, you can directly set the unwanted property to undefined.

Const object = {name: "Jane Doe", age:43}; object.age = undefined

You can also use the Map object because it is considered faster according to Bret,Map 's delete method.

11. Use asynchronous code to prevent thread blocking

You should know that JavaScript is synchronous and single-threaded. But in some cases, it may take a lot of time to execute a piece of code. In essence, synchronization means that this code will prevent other code statements from running until it finishes execution, which reduces the overall performance of the code.

But in fact, we can avoid this situation by implementing asynchronous code. Asynchronous code was previously written in the form of callbacks, but a new style of handling asynchronous code has been introduced in ES6. This new style is called promises.

Wait...

JavaScript is synchronous and single-threaded by default.

Why can you run asynchronous code while running on a single thread? This is where many people are confused. This is due to the JavaScript engine running under the browser shell. A JavaScript engine is a computer program or interpreter that executes JavaScript code. The JavaScript engine can be written in multiple languages. For example, the V8 engine that supports Chrome browsers is written in C++, while the SpiderMonkey engine that supports Firefox browsers is written in C and C++.

These JavaScript engines can handle tasks in the background. According to the Brian, the stack-aware functions of the Web API are called and handed over to the browser for processing. Once the browser processing completes these tasks, they are returned and pushed onto the stack as callbacks.

You may sometimes wonder how Node.js works without the help of a browser. In fact, the V8 engine that powers the Chrome also powers the Node.js.

twelve。 Use code segmentation

If you have experience with Google Light House, you will be familiar with a metric called "first contentful paint". It is one of the six metrics tracked by the performance section of the Lighthouse report.

First Contentful Paint (FCP) measures how long it takes the browser to render the first content of the DOM after the user navigates to the page. One of the best ways to get a higher FCP score for non-white images on a page is to use code segmentation. Code segmentation is a technique that sends only the necessary modules to the user at the beginning. Reducing the size of the valid content initially transmitted can significantly affect the FCP score.

Popular module packaging tools, such as webpack, provide code segmentation. You can load each module with the help of native ES modules.

13. Using asynchronous async and deferred defer

In modern websites, scripts are more intensive than HTML, they are larger in size and consume more processing time. By default, the browser must wait for the script to download, execute, and then process the rest of the page.

Large scripts may block the loading of web pages. To avoid this situation, JavaScript provides two techniques, async and latency. You just need to add these attributes to the

< script >

Label.

Async tells the browser to load the script without affecting the rendering of the page. In other words, the page does not have to wait for an asynchronous script for the content to be processed and displayed.

Latency is where the browser is told to load the script after the rendering is complete. If you specify both, async takes precedence in modern browsers, while older browsers that only support defer but not async will fall back to defer.

These two properties can greatly help you reduce page loading time.

14. Use Web Workers to run CPU-intensive tasks in the background

Web Workers allows scripts to be run in background threads. If you have some highly intensive tasks, you can assign them to web workers, and web workers will run them without interfering with the user interface. Once created, web worker can communicate with JavaScript code by sending messages to the event handlers specified by the JavaScript code. And vice versa.

After reading the above, do you have any further understanding of the 14 JavaScript code optimization suggestions? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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