Talk to Kong Yiji about front-end code optimization

The shop clerk got up immediately, and replied with a look of disdain: "Didn't it be said that it will be online until the end of the month? Who can stand this sudden attack? I have been working overtime for several days in a row; besides, that function was developed by Kong Yiji at that time. Do you want to use it?" Looking for him"; Hearing Kong Yiji's name, the shopkeeper's suppressed anger completely burned from his eyes, "The last project was that Kong Yiji left a lot of bugs, which made everyone very upset. Where is Kong Yiji?"

 

Kong Yiji, who had just come back from the restroom, heard his name 50 meters away from the inn, and hurried over in two steps: "Who is speaking ill of me behind my back? It is normal for there to be bugs in the code. Change it If you don’t change it, it will become...”, the waiter said disdainfully: “Kong Yiji, let’s take a look at the CSS you wrote. There will be more customers in the future, how can I deal with it”;

CSS Modularity

The waiter opened VsCode, and the code written by Kong Yiji suddenly appeared, a mess of HTML and CSS codes, which once made the waiter suspect that it was written by a new guy;

// 下拉菜单示例
// HTML
<div class="modalSelect">
  <div class="clickText" type="button" id="modalSelect">
    下拉菜单
    <span class="jiantou"></span>
  </div>
  <div class="listdiv">
    <div><span class="text">菜单一</span></div>
    <div><span class="text">菜单二</span></div>
    <div><span class="text">菜单三</span></div>
    <div><span class="text">菜单四</span></div>
  </div>
</div>

// CSS
.modalSelect {
	display: inline-block;
}

.modalSelect .clickText {
    color: #333;
    background-color: #fff;
    border: 1px solid #ccc;
}

.modalSelect .jiantou { // ... }
.modalSelect .listdiv {}
.modalSelect .listdiv div {}
.modalSelect .listdiv div .text {}
复制代码

"Kong Yiji, isn't it trivial to write styles with your technology? Now less/sass is so easy to use, you can do it." Kong Yiji smiled at the waiter in the shop: "Your second, you are still too young to develop front-end modules. I know the concept, hey, I have been developing for more than 10 years now, and I don’t bother to worry about these code details”;

"Is this the effect you want?"

HTML
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1">
    下拉菜单
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li><a href="#">菜单一</a></li>
    <li><a href="#">菜单二</a></li>
    <li><a href="#">菜单三</a></li>
  </ul>
</div>

// SCSS
.dropdown {
	.dropdown-toggle {
		.caret { // ... }
	}

	.dropdown-menu {
		> li {

		}
	}
}
复制代码

"Yes, this is the effect. HTML and CSS can also be developed modularly; Kong Yiji, please use sass in the future, and be consistent with everyone";

Kong Yiji let out an evil smile, and muttered in his heart: "Hehe, boy, you are still young, you don't know how difficult it is to find a job after the epidemic."

jQuery can still fight

Inadvertently, the steward discovered that there was still something in the code "$()\$.ajax()\$.extend()\$\$$, my God, it is 2023 now; the shopkeeper shouted: "Our project uses Vue or React", and the shop assistant replied: " Vue 2.x ";

"What happened to the $ in the code?"

The waiter in the shop replied again: "Ham, you don't know something. The new guys have just graduated from the private school, and they haven't been admitted as a scholar, and they haven't done any business. I heard that they are still teaching in the private school. jQuery ah "!

Kong Yiji on the side turned around and said: "A white cat is a black cat, as long as it catches mice, it is a good cat; customers only need to eat eggs, and don't care which chicken lays eggs, as long as jQuery can meet the needs"; Congealed, Kong Yiji felt a little embarrassed, pointed to the code and said: "Actually, it's okay for the new guy to do this, just pay attention to details and code optimization; for example:"

  • Extract function

In JavaScript development, we spend most of our time dealing with functions, so functions have good names, and the logic in the function body should be clear. If a function is too long and you have to add several comments to make the function readable, it is necessary to refactor these functions; if there is a piece of code in the function that can be isolated, then we'd better put these codes in into another separate function. This is a very common optimization work, and the main benefits of doing so are as follows:

  1. Avoid very large functions
  2. Independent functions facilitate code reuse
  3. Independent functions are easier to override
  4. If the independent function has a good name, it will play the role of a comment
function renderList(){
	$.get('/list', function(response){
		var fragment = [];
		for(var i = 0; i < response.length; i++){
			fragment.push('<div><span>'+item.name+'</span></div>');
		}
		
		$("#wrapper").html(fragment.join(""));
	}, 'json');
}

// 进行函数分解
// 获取数据
function getListsArray(renderCallback){
	$.get('/list', function(responseArray){
    typeof renderCallback === 'function' && renderCallback(responseArray);
	}, 'json')
}

// 组装列表DOM
function getListFragment(listArray){
    var fragment = [];
		for(var i = 0; i < listArray.length; i++){
			fragment.push('<div><span>'+listArray[i].name+'</span></div>');
		}
    return fragment.join("");
}

// 替换DOM
function replaceDOM(container, element){
  $(container).html(element);
}


var getListAndRender = function(container){
  getListsArray(function(responseArray){
    replaceDOM(container, getListFragment(responseArray));
  });
}

getListAndRender("#wrapper");
复制代码
  • Merge duplicate conditional fragments

If there are some conditional branch statements in a function body, and some repeated codes are scattered inside these conditional branch statements, then it is necessary to merge and deduplicate the work


var paging = function(){
  if(currentPage <= 0){
    currentPage = 0;
    jump( currentPage );
  }else if(currentPage >= totalPage){
    currentPage = totalPage;
    jump(currentPage);
  }else{
    jump(currentPage);
  }
}

// 改进
var paging = function(){
  if(currentPage <= 0){
    currentPage = 0;
  }else if(currentPage >= totalPage){
    currentPage = totalPage;
  }

  jump(currentPage);
}

复制代码
  • Use cycles wisely

  • Pass object arguments instead of long argument lists

Sometimes a function may receive multiple parameters, and the more parameters, the more difficult the function is to understand and use. People who use this function must first understand the meaning of all parameters, and be careful when using it, so as not to pass a certain parameter or reverse the position of two parameters. If we want to add a new parameter among the third parameter and the fourth parameter, it will involve many code modifications

  • Minimize the number of parameters

If you need to pass in multiple parameters when calling a function, then this function is daunting. We must figure out what these parameters represent, and we must carefully pass them into the function in order. And if a function can be used without passing any parameters, this kind of function is very popular. In actual development, it is inevitable to pass parameters to functions, but we should minimize the number of parameters received by functions

  • Use less ternary operators

Some guys like to use the ternary operator on a large scale to replace the traditional if and else. The reason is that the ternary operator has high performance and less code. However, these two reasons are actually difficult to hold water. Even if we assume that the efficiency of the ternary operator is really higher than that of if and else, the difference is completely negligible. In actual development, even if a piece of code is looped a million times, the time overhead of using the ternary operator is at the same level as using if and else. Similarly, compared to the loss of code readability and maintainability, the amount of code saved by the ternary operator is also negligible. There are many ways to make JS files load faster, such as compression, caching, using CDN and domain names, etc.

// 如果条件分支逻辑简单且清晰,这无碍我们使用三目运算符:
var global = typeof window !== "undefined" ? window : this;

// 如果条件分支逻辑非常复杂,那我们最好的选择还是按部就班地编写if 、 else 。 if 、 else 语句的好处很多是:
1. 阅读相对容易
2. 修改的时候比修改三目运算符周围的代码更加方便

复制代码
  • async/await solves the callback problem

"Haha, what the old man wants to say is:" You can't be informal when writing code. Being able to write functionally sound, easy-to-maintain, and easy-to-read code does not happen overnight. It requires everyone to be aware of code quality, insist on code review, learn from each other's strengths, and avoid accumulating technical debt." Kong Yiji has a sense of being a teacher The feeling that saying these words made him feel worthy of his status as a masturbator for many years

ES6 feature enhancements

"Kong Yiji, everyone is using ES6 now, and you also told us how to use the commonly used methods in daily coding, how to optimize them, or how to make them more efficient", several newcomers surrounded Kong Yiji said in a hurry; "Well, let me tell you, ES6 is very easy to use, and many methods are very cool to use, such as:"

Array methods: map, filer, isArray, reduce, async/await

  • chain call of map with filter

Many methods of arrays can be used in chains. There is a premise: the data returned by the previous method is still an array

// 获取score >= 90 的student,并输出['name: score']格式数据
const students = [
  {name: 'James', score: 98},
  {name: 'lucy', score: 80},
  {name: 'rose', score: 90},
  {name: 'fox', score: 88}
];


let result = students.filter(student=>student.score >= 90)
                     .map(student=>`${student.name}: ${student.score}`);
复制代码
  • reduce uses
// 统计所有学生的分数之和
const students = [
  {name: 'James', score: 98},
  {name: 'lucy', score: 80},
  {name: 'rose', score: 90},
  {name: 'fox', score: 88}
];

let total = students.reduce((result, student, studentIndex, array)=>{
  result += student.score;
  return result;
}, 0);
复制代码
  • async/await Kong Yiji pointed to async/await and said: "This thing is interesting. The technology of the 21st century is really enviable. Once upon a time, when you stepped out of one barrier, you fell into another quagmire; the callback hell back then made labor and capital miserable. Looking back, Promise.then made me confused again, you guys are blessed, if you can use async/await, use it as much as possible";
update = async(params)=>{
  let resultA = await this.dispatch("updateState", { params });
  let resultB = await this.dispatch("updateState", { params: resultA })
  let resultC = await this.dispatch("updateState", { params: resultB })
}
复制代码

"Well, I got it, GET is here, Kong Yiji is amazing!", the new guy praised;

"Okay, okay, I'm also a taster, or I didn't even pass the exam as a scholar, so don't make fun of me, today is just an appetizer!"

Seeing that Kong Yiji was chatting happily with the new guy, the shopkeeper murmured: "Old Youtiao, after so many years in business, he didn't even get a talent, so he was smacking in front of the new guy";

"Kong Yiji, I found out that you wrote a bug again, hurry up and take a look!"

"Come on!"

"Guys, let's go, let's talk to you here today, and I'll talk to you after I fix the bug; if you want to know what's going on, please listen to the next chapter to break it down";

epilogue

This story is purely fictitious, and any similarity is purely coincidental;

  • I laughed at "Kong Yiji" when I was young, but now I have become "Kong Yiji"
  • Please pay attention to Kong Yiji to improve the code example when you are free
  • postscript please look forward to

 

Guess you like

Origin blog.csdn.net/a1014981613/article/details/130302726