javaScript代码优化

2020-10-20  本文已影响0人  浅忆_0810

1. 检测工具

JSBeach


2. 慎用全局变量

全局变量特点:

// 不推荐
var i, str = ''
for (i = 0; i < 1000; i++) {
  str += i
}

// 推荐
let str = ''
for (let i = 0; i < 1000; i++) {
  str += i
}

3. 缓存全局变量

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>缓存全局变量</title>
</head>
<body>
  <input type="button" value="btn" id="btn1">
  <input type="button" value="btn" id="btn2">
  <input type="button" value="btn" id="btn3">
  <input type="button" value="btn" id="btn4">
  <p>1111</p>
  <input type="button" value="btn" id="btn5">
  <input type="button" value="btn" id="btn6">
  <p>222</p>
  <input type="button" value="btn" id="btn7">
  <input type="button" value="btn" id="btn8">
  <p>333</p>
  <input type="button" value="btn" id="btn9">
  <input type="button" value="btn" id="btn10">

  <script>
    // 不推荐
    function getBtn() {
      let oBtn1 = document.getElementById('btn1');
      let oBtn3 = document.getElementById('btn3');
      let oBtn5 = document.getElementById('btn5');
      let oBtn7 = document.getElementById('btn7');
      let oBtn9 = document.getElementById('btn9');
    }
        
    // 推荐
    function getBtn2() {
      let obj = document;
      let oBtn1 = obj.getElementById('btn1');
      let oBtn3 = obj.getElementById('btn3');
      let oBtn5 = obj.getElementById('btn5');
      let oBtn7 = obj.getElementById('btn7');
      let oBtn9 = obj.getElementById('btn9');
    }
  </script>
</body>
</html>

4. 通过原型对象添加附加方法

// 不推荐
var fn1 = function() {
  this.foo = function() {
    console.log(11111)
  }
}
let f1 = new fn1()

// 推荐
var fn2 = function() {}
fn2.prototype.foo = function() {
  console.log(11111)
}
let f2 = new fn2()

5. 选择最优的循环方法

var arrList = new Array(1, 2, 3, 4, 5);

arrList.forEach(function(item) {
  console.log(item);
})

for (var i = 0,len = arrList.length; i < len; i++) {
  console.log(arrList[i]);
}

for (var i in arrList) {
  console.log(arrList[i]);
}

6. 文档碎片优化节点添加

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>优化节点添加</title>
</head>
<body>
  <script>
    // 不推荐
    for (var i = 0; i < 10; i++) {
      var oP = document.createElement('p');
      oP.innerHTML = i;
      document.body.appendChild(oP);
    }
        
    // 推荐
    const fragEle = document.createDocumentFragment()
    for (var i = 0; i < 10; i++) {
      var oP = document.createElement('p');
      oP.innerHTML = i;
      fragEle.appendChild(oP);
    }
    document.body.appendChild(fragEle);

  </script>
</body>
</html>

7. 克隆优化节点

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>克隆优化节点操作</title>
</head>
<body>
  <p id="box1">old</p>

  <script>
    // 不推荐
    for (var i = 0; i < 3; i++) {
      var oP = document.createElement('p');
      oP.innerHTML = i; 
      document.body.appendChild(oP);
    }
        
    // 推荐
    var oldP = document.getElementById('box1')
    for (var i = 0; i < 3; i++) {
      var newP = oldP.cloneNode(false);
      newP.innerHTML = i;
      document.body.appendChild(newP);
    }

  </script>
</body>
</html>

8. 减少判断层级

// 不推荐
function doSomething(part, chapter) {
  const parts = ['ES2016', '工程化', 'Vue', 'React', 'Node'];
  if (part) {
    if (parts.includes(part)) {
      console.log('属于当前课程');
      if (chapter > 5) {
        console.log('您需要提供 VIP 身份');
      }
    } else {
      console.log('请确认模块信息');
    }
  }
}

// 推荐
function doSomething(part, chapter) {
  const parts = ['ES2016', '工程化', 'Vue', 'React', 'Node'];
  if (!part) {
    console.log('请确认模块信息');
    return;
  }
  if (!parts.includes(part)) return;
  console.log('属于当前课程');
  if (chapter > 5) {
    console.log('您需要提供 VIP 身份');
  }
}

doSomething('ES2016', 6);

9. 减少数据读取次数

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>任务管理器监控内存变化</title>
</head>
<body>
  <div id="skip" class="skip"></div>

  <script>
    var oBox = document.getElementById('skip');
    
    // 不推荐
    function hasEle(ele, cls) {
      return ele.className == cls;
    }
        
    // 推荐
    function hasEle(ele, cls) {
      var className = ele.className;
      return className == cls;
    }
    
    console.log(hasEle(oBox, 'skip'))
  </script>
</body>
</html>

10. 减少声明和语句数

var oBox = document.getElementById('skip');

// 不推荐
let test = ele => {
  let w = ele.offestWidth;
  let h = ele.offestHeight;
  return w + h;
}

// 推荐
let test = ele => {
  return ele.offestWidth + ele.offestHeight;
}

console.log(test(oBox));

11. 使用惰性函数

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>任务管理器监控内存变化</title>
</head>
<body>
  <button id="btn">点击</button>

  <script>
    var oBtn = document.getElementById('btn');
    
    function foo() {
      console.log(this);
    }
        
    // 不推荐
    function addEvent(obj, type, fn) {
      if(obj.addEventListener) {
        obj.addEventListener(type, fn, false);
      }else if(obj.attactEvent) {
        obj.attactEvent('on' + type, fn);
      }else {
        obj['on' + type] = fn;
      }
    }

    // 推荐
    function addEvent(obj, type, fn) {
      if(obj.addEventListener) {
        addEvent = obj.addEventListener(type, fn, false);
      }else if(obj.attactEvent) {
        addEvent = obj.attactEvent('on' + type, fn);
      }else {
        addEvent = obj['on' + type] = fn;
      }
      return addEvent;
    }
    
    addEvent(oBtn, 'click', foo);
  </script>
</body>
</html>

12. 使用事件委托

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>任务管理器监控内存变化</title>
</head>
<body>
  <ul id="content">
    <li>vue</li>
    <li>react</li>
    <li>node</li>
  </ul>

  <script>
    // 不推荐
    var list = document.querySelectorAll('li');
    function showTxt(e) {
      console.log(e.target.innerHTML);
    }
    for(let item of list) {
      item.onclick = showTxt;
    }
        
    // 推荐
    var oUl = document.getElementById('content');
    oUl.addEventListener('click', showTxt, true);
    function showTxt(e) {
      var target = e.target;
      if(target.nodeName.toLowerCase() == 'li') {
        console.log(target.innerHTML);
      }
    }
  </script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读