js规范-DOM操作

53 阅读1分钟

DOM操作

DOM操作

  • 避免在document上频繁的DOM操作,可以用 fragment文档片段

  • 最快获取dom的方法

     <div id="zero2one"></div>
     const el = document.getElementById('zero2one')  
     console.log(el)   // <div id="zero2one"></div>
    
     console.log(zero2one)   // <div id="zero2one"></div>
    
  • 使用requestAnimationFrame 代替setInterval

    window.requestAnimFrame = (function () {
         return window.requestAnimationFrame ||
             window.webkitRequestAnimationFrame ||
             window.mozRequestAnimationFrame ||
             function (callback) {
                 window.setTimeout(callback, 1000 / 60);
             };
     })();
    
  • 函数节流(throttle) 或 函数去抖(debounce),限制某一个方法频繁触发

	防抖
	function debounce(handle, delay) {
	    var timer = null;
	    return function () {
	        var _self = this,
	            _args = arguments;
	        clearTimeout(timer);
	        timer = setTimeout(function () {
	            handle.apply(_self, _args)
	        }, delay)
	    }
	}
       good: ✅   
       1.用于用户输入模糊匹配,节约请求资源
       2. window触发resize,限制只触发次数
       window.addEventListener('resize', lodash.debounce(handle, 1000));


	节流
	function throttle(handler, wait) {
	    var lastTime = 0;
	    return function (e) {
	        var nowTime = new Date().getTime();
	        if (nowTime - lastTime > wait) {
	            handler.apply(this, arguments);
	            lastTime = nowTime;
	        }
	    }
	}
      good: ✅   
      1.重复点击触发
      2. 监听滚动事件,例如是否划到底部自动加载更多
      window.addEventListener('scroll', lodash.throttle(handle, 1000));
  • 及时消除对象引用、清除定时器、清除事件监听器