I recently read the book efficient Front-end: Efficient Web Programming and Optimization Practices, which introduces optimization practices and front-end fundamentals of efficient front-end programming. This article introduces some examples of efficient programming with a personal understanding.

Don’t use JS for problems you can solve with HTML/CSS

Customize radio/checkbox styles

The native Radio /checkbox style in the form varies from browser to browser. One way to unify styles is to draw your own div/span and listen for click events. This means that the logic control has to be written entirely, and the native event change cannot be used.

Here you can implement custom styling by providing the pseudo class Checked via CSS. The idea is to write a checkbox and a span with a custom style inside a label. The checkbox is always hidden.

<style>
input[type=checkbox]{
    display: none;
}
/* Unchecked checkbox style */
.checkbox{ /* Implement */ }
input[type=checkbox]:checked + .checkbox{ /* Implement */ }
</style>
<label for="apple">
    <input type="checkbox" id="apple">
    <span class="checkbox"></span>
</label>
Copy the code

You need to display different styles according to the number

There are 1 to 3 items to be displayed on the same line, but the number of items is not necessarily the same. If there is only one item, the width of the item is 100%; if there are two items, the width is 50%; if there are three items, the width is 33%. Obviously you can do it in JS, but that’s a little tedious.

We can use CSS3’s first-child and nth-last-Child to distinguish the number

<style>
li {
    width: 100%
}
li:first-child:nth-last-child(2).li:first-child:nth-last-child(2) ~ li{
    width: 50%
}
li:first-child:nth-last-child(3).li:first-child:nth-last-child(3) ~ li{
    width: 33%
}
</style>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
Copy the code

Draw a triangle with CSS

This technique should be common, draw the triangle by setting the width and height to 0 and setting the border of only one side. Here are some other ways to draw triangles:

// Border -top: 50px solid transparent; border-bottom: 50px solid transparent; border-left: 50px solid #000; // border-left: 60px solid transparent; border-right: 0 solid transparent; border-bottom: 40px solid #000; // border-left: 28px solid transparent; border-right: 28px solid transparent; border-bottom: 40px solid #000;Copy the code

Reduce front-end code coupling

The coupling of JS/CSS/HTML

It is not recommended to change style properties directly in JS. You should add and delete classes to control style, except scroll and Mousemove

The strategy pattern

// common
function popCallback(popType){
    switch(popType){
        case: "favHouse":
            favHouse();
            break;
        case: "saveSearch":
            saveSearch();
            break; }}// strategy
var popCallback = {
    favHouse: function(){ /*do sth.*/ },
    saveSearch: function(){ /*do sth.*/}}if(typeof popCallback[popType] === "function"){
    popCallback[popType]();
}
Copy the code

JS writing optimization

Write code in a strongly typed style

Static type checkers (Flow, TypeScript) can also be used in projects to optimize code. Here are some good tips:

  • When you define a variable, specify the type
var num = 0,
    str = ' ',
    obj = null;
Copy the code
  • Do not arbitrarily change the type of a variable
// bad
var num = 5;
num = "-" + num;
// good 
var num = 5;
var sign = "-" + num;
Copy the code
  • The return type of a function should be determined
// bad
function getPrice(count){
    if(count < 0) return "";
    else return count * 100;
}
// good
function getPrice(count){
    if(count < 0) return - 1;
    else return count * 100;
}
Copy the code

Reduce scope lookups

The global scope is complex, so finding attributes is slow. The search for local effects is quick

// bad
var url = "";
if(window.location.protocal === "https:"){
    url = "wss://xxx.com" + window.location.pathname + window.location.search;
}

// good is cached as a local variable
var url = "";
var location = window.location;
if(location.protocal === "https:"){
    url = "wss://xxx.com" + location.pathname + location.search;
}
Copy the code

Avoid using ==

We should avoid the use of == in our code. We should use === in order to avoid some unexpected consequences of JS type conversions.

If (obj == null)

Simplify code with ES6

  • Use arrow functions instead of small functions
var nums = [4.8.1.9.0];
nums.sort((a, b) = > b - a);
Copy the code
  • String splicing
var tpl =
` 
      
1
`
; var url = `/list? page=${page}&type=${type}`; Copy the code
  • Block-level scope variables
var tasks = [];
for(let i = 0; i <= 4; i++){
    tasks.push(function(){
        console.log("i is " + i);
    });
}
for(var j = 0; j < tasks.length; j++){
    tasks[j]();
}
Copy the code

Enhance the user experience

Add Loding effect

Common Loading includes image Loading, AJAX request, and file uploading progress bar. There’s also the more recent thing called skeleton loading.

Style, copy

In this section, you can take a look at some basic concepts and design principles of UI libraries, such as ANTD-Design

The use of good Chrome Devtools

For Chrome Devtools debugging tips, see the official documentation in F12.

print

  • console.tablePrint an array of objects
  • console.dirCan recursively print all properties of the object, print a DOM node

Check for unused CSS/JS

The Coverage TAB of DevTools is red for the Coverage TAB that is not used and green for the Coverage TAB that is used

Research to redraw

Devtools has a Renders Renders for researching redraw

conclusion

There are many optimization practice points in the book, and I will introduce some relatively common ones. In fact, the optimization practice gives a better plan, but the actual situation should be combined to choose the plan.