I believe everyone knows that JavaScript is a full-stack development language, and JS can be seen on the browser, mobile phone, and server side. This article will share some efficient JavaScript best practices to improve your understanding of the underlying JS and implementation principles.
Data storage
There is a classic problem in the computer discipline that achieves optimal read and write performance by changing the location of data storage. In JavaScript, the location of data storage can have a significant impact on code performance. If you can create objects with {}, do not use new Object. If you can create arrays with [], do not use new Array. The access speed of literals in JS is higher than that of objects. The deeper the variable is in the scope chain, the longer the practice required for access. For such variables, local variables can be saved through cache, reducing the number of accesses to scope chains, there is not much difference between point notation (object.name) and operator (object[name]). Only Safari will have a difference, and points are always faster
cycle
There are several common loops in JS:
for(var i = 0; i < 10; i++) { // do something} for(var prop in object) { // for loop object} [1,2].forEach(function(value, index, array) { // function-based loop})Needless to doubt, the first method is native, with the lowest performance consumption and the fastest speed. The second method for-in generates more overhead (local variables) every iteration, and its speed is only 1/7 of the first type. The third method obviously provides a more convenient loop method, but its speed is only 1/8 of the ordinary loop. Therefore, you can choose the appropriate loop method according to your project situation.
Event delegation
Just imagine adding an event to each A tag on the page. Will we add an onClick to each tag? This situation may affect performance when there are a large number of elements in the page that need to be bound to the same event processing. Each binding event increases the burden on the page or during the run. For a rich front-end application, too many bindings will occupy too much memory on a page with heavy interactions. A simple and elegant way is event delegation. It is an event-based workflow: capture layer by layer, reach the target, bubble up layer by layer. Since there is a bubble mechanism for events, we can handle events starting 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; //If it is not the A tag, I will exit if(target.nodeNmae !=== 'A') { return } //Print the link address of A console.log(target.href) }Repaint and Rearrange
After the browser downloads HTML, CSS, and JS, two trees will be generated: the DOM tree and the rendering tree. When Dom's geometric properties change, such as Dom's width and height, or color, position, 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%;
By modifying the three properties in the above method, the browser will re-paint three times. In some cases, reducing this re-arrangement can improve the browser's rendering performance. The recommended method is as follows: Only one operation is performed and three steps are completed:
bodystyle = document.body.style; bodystyle.cssText 'color:red;height:1000px;width:100%';
JavaScript Loading
IE8, Firefox3.5, and Chrome2 all allow the required download of JavaScript files. So <script> won't block other tag downloads. Unfortunately, the JS download process will still block downloading of other resources, such as images. Although the latest browsers improve performance by allowing parallel downloads, script blocking is still a problem. Therefore, it is recommended to place all <script> tags at the bottom of <body> tags to minimize the impact on the rendering of the entire page and avoid users from seeing a blank space
High-performance JS file deployment
Since you already know 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 website speedup. Therefore, merging all JS files in the product environment will reduce the number of requests, thereby speeding up page rendering. In addition to merging JS files, we can also compress JS files. Compression refers to stripping out parts of a file that are not related to the run. The 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 reduce the length of local variables, such as:
var myName = "foo" + "bar"; // After compression, it becomes var a = "foobar";
Cache JS files
Caching HTTP components can greatly improve the user experience of website return visits. The web server uses the "Expires HTTP response header" to tell the client how long a resource should be cached. Of course, cache also has its own flaws: When the application is upgraded, you need to make sure that the user downloads the latest static content. This problem can be solved by changing the file name of the static resource. You may see the browser reference jsapplication-20151123201212.js in the product environment. This is to save the new JS file in a timestamp, thereby solving the problem of cache not being updated.
Summarize
Of course, efficient JS is not just about these things that can be improved. If some performance losses can be reduced, we can use JavaScript to develop more efficiently.