In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you 14 JavaScript code optimization skills for front-end developers. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.
We have no control over the hardware specifications of the devices for users to access the website, the devices for end users to access the site are either high-end or low-end, and the Internet connection is good or poor, which means that we must optimize the site as much as possible to meet the needs of all users. At the same time, according to W3Tech, nearly 96% of the world's websites use JavaScript,JavaScript, which has become one of the most popular programming languages in history.
Here are some tips for you to better optimize your JavaScript code for better performance.
By the way, make sure that JS components are shared and reused to strike the right balance between high-quality code that takes time to generate and reasonable delivery time. You can use popular tools such as Bit (Github) to share components in your project (vanilla JS,TS,React,Vue, etc.) to the component center of Bit without wasting too much time.
1. Remove unused code and features
The more code your application contains, the more data you need to transfer to the client. The longer it takes for browsers to parse the code, and sometimes some features may not be used at all. It is best to keep this extra code only in the development environment, rather than in the production environment, so that it does not burden the client browser with useless code.
Keep asking yourself if a feature, feature, or code is necessary. You can remove unused code manually or using tools such as Uglify or google's closurecompiler, or even remove unused code from your application using a technique called shaken tree optimization (tree shaking).
Balers such as Webpack provide this technique, and if you want to delete unused npm packages, you can use the npm prune command.
Image source: unsplash
two。 Cache at any time
Caching improves the speed and performance of the site by reducing latency and network traffic, thereby reducing the time required to display resources. This can be achieved through caching application program interface (Cache API) or hypertext transfer protocol cache (HTTPcaching). The above caching mechanism can process and regenerate the cache when certain conditions are met, such as publishing new content.
3. Avoid memory leaks
The high-level language JS is responsible for several low-level management, such as memory management. Garbage collection mechanisms are common in most programming languages. In popular terms, the garbage collection mechanism simply collects and releases memory that has been allocated to the target object, which is not used in any part of the program. In programming languages such as C, developers must use the malloc () and dealloc () functions to allocate and free memory.
Although JavaScript performs garbage collection automatically, sometimes it is not perfect. In JavaScript ES6, maps (Map) and sets (Set) are introduced along with their "weaker" siblings. This "weaker" class is called WeakMap and WeakSet, and their references to objects are "weak", allowing garbage collection of unreferenced values, thereby preventing memory leaks.
4. Jump out of the cycle as soon as possible
Large cycles are bound to consume a lot of valuable time, so jump out of the cycle as soon as possible. The keywords break and continue can do this. It is your responsibility to write the most efficient code. In the following example, if you don't break the loop, the code will run the loop 1000000000 times, which obviously leads to overloading.
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中的闭包可以从内部函数访问外部函数。每次创建函数时都会创建闭包,而不是调用。即使外部函数已经返回,内部函数也可以访问外部作用域的变量。 通过以下两个实例来解释这一点: 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 that returns to the variable cityOfCustomer can access the constant of the external function findCustomerCity (). Whenever an internal function is called, its name is passed as an argument, and there is no need to instantiate the constant again.
6. Avoid using the delete keyword
The delete keyword is used to remove properties from an object. Users have complained about the performance of the delete keyword, and deficiencies are expected to be fixed in future updates. You can choose to simply set unwanted properties to undefined.
Const object = {name: "Jane Doe", age:43}; object.age = undefined
You can also use Map objects, which, according to Brett, is faster.
7. Minimize DOM access
Compared with other JavaScript statements, accessing DOM is slow. Changes to DOM trigger a redrawing of the layout, causing the site to run more slowly. Access a single DOM element at once and use it as a local variable to reduce the number of visits. When the task is complete, be sure to set the variable to null to remove the value of the variable. This triggers the garbage collection mechanism to prevent memory leaks.
8. Compressed file
Image source: takscan
Use a compression method such as Gzip to reduce the size of the JavaScript file. In view of the reduction of the download materials required by the browser, the performance of the website has also improved. Compression reduces file size by 80%.
9. Reduce the final code
Some people think that reduction and compression are the same, but this is not the case. Compression uses a special algorithm to change the output size of the file, while reduction requires the removal of comments and extra spaces in the JavaScript file. This process can be done with the help of many tools and packages, all of which can be found online. Downsizing has become a standard practice for page optimization and a major part of front-end optimization.
Reducing file size reduces file size by 60%.
10. Use throttling (throtte) and de-jitter (debounce)
Throttling and de-jitter strictly control the number of times the code handles events.
Throttling specifies the maximum number of times a function can time out. 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, which reduces the load on the code.
De-dithering specifies the minimum duration of the function, which is the time the function has been run again since the last execution. In other words, "this function is executed only after 600 milliseconds without calling the function." This means that the function will not be called for 600 milliseconds from the last time it was executed.
11. Use async and latency
Image source: unsplash
In modern websites, scripts are denser, larger, and take longer to process than Hypertext markup language (HTML). By default, the browser must wait for the script to be downloaded and executed before processing the rest of the page. This can lead to huge scripts that prevent web pages from loading. To avoid this, JavaScript provides two techniques called async and latency, and you just need to add these attributes to the tag.
Async tells the browser to load the script without affecting the rendering. In other words, instead of waiting for an asynchronous script, the page processes and displays the content. Delay tells the browser to load the script after the rendering is complete. If both are specified, asynchrony takes precedence on modern browsers, while older browsers that support latency but do not support asynchrony fall back to latency.
These two properties can greatly reduce page load time.
twelve。 Use asynchronous code to prevent thread blocking
JavaScript is synchronous and single-threaded by default. But there is a time code that takes a lot of time to calculate. In essence, synchronization means that a piece of code prevents other code statements from running until the end of execution. This will degrade the overall performance of the site. But we can avoid this by implementing asynchronous code. Asynchronous code was written in callback form, but ES6 introduced a new style of handling asynchronous code called promises.
But how can I run asynchronous code while running on a single thread? This is where a lot of people are confused. Everything is made possible by the JavaScript engine running in the background of the browser. 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 Google browser is written in C++, while the Spider Monkey engine that supports Firefox is written in C and C++.
These JavaScript engines can handle tasks in the background. According to Brian, the function of the call stack to identify the web application interface (Web API) is submitted to the browser for processing. Once the browser completes these tasks, they return and are pushed onto the stack as callbacks.
How does Node.js run without a browser? In fact, the V8 engine that drives Google browser also supports Node.js.
13. Use code split
Image source: unsplash
If you have any experience with Google Light House, you are sure to be familiar with a metric called initial content rendering (first contentful paint). This is one of the six indicators tracked by the performance section of the lighthouse report.
Initial content rendering (FCP) measures the time it takes for the browser to render the first DOM content after the user navigates to the page. Images, non-white elements, and scalable vector graphics (SVG) on the page are considered DOM content, and nothing in the iframe is included.
One of the best ways to get a higher FCP score is to use code splitting. Code splitting is a technique that initially sends only the necessary modules to the user. The FCP fraction is greatly affected by reducing the size of the initial transmitted payload. Popular module managers, such as webpack, provide code splitting capabilities. You can also load a single module with the help of a native ES module.
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 high-intensity tasks, you can assign them to Web Workers,Web Workers to run them without interfering with the user interface. Once created, Web Workers can send messages to the event handlers specified by the JavaScript code to communicate with that code, and vice versa.
Image source: unsplash
These are the 14 JavaScript code optimization techniques shared by Xiaobian for front-end developers. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.