반응형

# lodash

  • 자바스크립트 라이브러리 중 하나로 또다른 자바스크립트 라이브러리인 제이쿼리(jquery)와 많이 사용 된다.
  • lodash, jquery 사용에 따른 퍼포먼스 차이가 많이 난다.

## 사용하는 방법

  • lodash 불러오기 ( 사용 시 _. 로 시작 )
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
  •  jquery 불러오기 ( 사용 시 $ 로 시작 )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

 

## lodash 적용 예제 (윈도우 넓이 구하기)

### lodash 미 적용

  • lodash 미 적용 시 코드. 
  • 화면 변동에 따라 계속 실행 됨.

See the Pen lodash 미 적용 by dlagusgh1 (@dlagusgh1) on CodePen.

console.clear();
var $window = $(window);

$window.resize(function() {
	var windowWidth = $window.width();
    
    console.log("windowWidth : " + windowWidth);
});


== 위와 같은 코드 ==
console.clear();
var $window = $(window);

function a() {
	var windowWidth = $window.width();
    
    console.log("windowWidth : " + windowWidth);
}

$window.resize(function() {
	a();
});


== 위와 같은 코드 ==
console.clear();
var $window = $(window);

var a = function () {
	var windowWidth = $window.width();
    
    console.log("windowWidth : " + windowWidth);
}

$window.resize(function() {
	a();
});

## lodash 적용 코드. ( _.Throttle 적용 )

  • _.throttle (함수, 시간);
  • 입력 주기를 방해하지 않고, 일정 시간 동안의 입력을 모아서 한 번씩 출력을 제한.

See the Pen lodash _.throttle 적용 by dlagusgh1 (@dlagusgh1) on CodePen.

console.clear();
var $window = $(window);

var b = _.throttle(function () {
	var windowWidth = $window.width();
    
    console.log("windowWidth : " + windowWidth);
}, 1000);	// 1초에 1번 실행

$window.resize(function() {
	b();
});

## lodash 적용 코드. ( _.debounce 적용 )

  • _.debounce (함수, 시간);
  • 입력 주기가 끝나면(입력이 완료되면), 입력한 시간 만큼 딜레이 후 출력한다.
  • 여러번 발생하는 이벤트에서, 가장 마지막 이벤트만 실행되도록 만드는 것.
  • 회원가입 폼 등에 많이 사용된다.

See the Pen lodash _.debounce 적용 by dlagusgh1 (@dlagusgh1) on CodePen.

console.clear();
var $window = $(window);

var c = _.debounce(function () {
	var windowWidth = $window.width();
    
    console.log("windowWidth : " + windowWidth);
}, 1000);	// 1초에 1번 실행

$window.resize(function() {
	c();
});

## _.throttle 와 _.debounce 차이점

이벤트를 언제 발생 시킬지 시점의 차이가 있다.

debounce : 입력이 끝날때까지 무한정 대기

throttle : 입력이 시작되면 일정 주기를 계속 실행한다.

 

반응형

+ Recent posts