컨텐츠 바로가기


사용자 가이드 상세


jQuery 퍼포먼스 향상 팁

- selctor 사용 -

1. 가능하면 ID selector를 사용.


- jQuery에서는 document.getElementById()를 사용하기 때문에 ID selector가 빠르다. (가장 빠른 것은 native javascript)

  // Slow
  $('.header');
 
  // Fast
  $("#header");
  // Faster
  document.getElementById("header");

2. class selector를 사용할 때에는 element type을 selector 앞에 사용하지 않음.
  // Slow
  var $product = $('div.product');
 
  // Fast
  var $product = $('.product');

3. 특정 id를 기준으로 자식 element 목록을 탐색할 때는 .find()를 사용.

- 제이쿼리에서 사용하는 셀렉터가 씨즐 셀렉터(Sizzle Selector)인데, .find()를 사용하면 sizzle selector를 거치지 않고 바로 탐색해서 더 빠르다.

  // Slow
  var $productId = $('#product div.item');
 
  // Fast
  $productId = $('#product').find('div.item');


  $parent = $('#parent');// 하위 내용 보여줄 경우
 
  $('.child', $parent).show(); // 5~10% 느림
  $('.child', $('$parent')).show(); //23% 느림
  $parent.children('.child').show(); // 50% 정도 느림
  $('#parent > .child').show(); // 70% 정도 느림
  $('#parent .child').show(); // 77% 느림
  $parent.find('.child').show(); // 가장 빠름

4. 복잡한 selector는 피함.
  // Slow
  $('.info table.data td.address');
 
  // Fast
  $('.info td.address');

5. 전역 selector는 피함.
  // Slow
  $(‘:visible, :hidden’)
  $(‘[attribute=value]’)
  $('.buttons > *');
  $('.category :radio');
  $('.category *:radio');
 
  // Fast
  $('.category input:radio');

6. ID selector를 사용할때는 다른 것과 같이 사용하지 않음.

- document.getElementById()를 사용하기 때문에 혼합해서 사용하면 빠르지 않다.

  // Slow
  $('#outer #inner');
  $('div#inner');
  $('.outer-container #inner');
 
  // Fast
  $('#inner');


- DOM 조작 -

1. 캐싱(Caching) 사용.


- 자주 불러오거나, 시간이 걸렸던 작업등을 변수에 저장해서 다시 작업 한다.

  // Bad
  $('.test').css({'display':'block','background','#000'});
 
  // Good
  .selected { display:block; background:#000; }
  $('.test').addClass('selected');


2. element의 유무를 확인하고 실행.
  // Bad
  $('#nosuchthing').slideUp();
 
  // Good
  var $mySelection = $('#nosuchthing');
  if ($mySelection.length) {
      $mySelection.slideUp();
      ...
  }

3. jQuery에 css 스타일을 섞어서 직접 사용하지 않음.


- css에서 class를 정의하고, 자바스크립트에서 class를 추가, 삭제, 수정하여 스타일을 조작 한다.

  // Bad
  $('.test').css({'display':'block','background','#000'});
 
  // Good
  .selected { display:block; background:#000; }
  $('.test').addClass('selected');



- 이벤트 처리 -

1. HTML 마크업에 직접 이벤트를 걸지 않음.


- 디버깅이 어렵고, 동적으로 쉽게 이벤트를 생성하고 삭제하는 것이 어렵다.

  // Bad
  <a id="myLink" href="#" onclick="myEventHandler();">my link</a>
 
  // Good
  $('#myLink').on('click', myEventHandler);


2. 이벤트 위임을 사용.


- 이벤트 위임(Event delegate)을 사용하면 동적으로 추가 또는 수정되는 자식 엘리먼트들의 이벤트도 함께 처리할 수 있는 이점이 있다.

  $("#parent-container").on("click", "a", delegatedClickHandler);
  function delegatedClickHandler(){...}



- 메서드 체이닝 -

1. 메서드 체이닝을 사용.


- 메서드 체이닝은 변수 캐싱 및 selector를 여러번 호출하지 않아도 되는 이점이 있다.

  // Bad
  $(this).slideUp();
  $(this).addClass('selected');
 
  // Good
  $(this).slideUp().addClass('selected');


2. 메서드 체이닝을 3번 이상하면 가독성에 문제가 있으니 줄바꿈을 사용.
  $(this)
    .slideUp()
    .addClass('selected')
    .on('click', myClickHandler);

3. 같은 메서드를 2번 이상 사용할 경우에는 메서드 체이닝보다는 객체 리터럴을 사용.
  // Bad
$myLink.attr('href', '#').attr('title', 'my link').attr('rel', 'external');

  // Good
  $myLink.attr({
    href: '#',
    title: 'my link',
    rel: 'external' 
  });


- jQuery 객체 -

1. jQuery 객체 사용을 최소화.


- 꼭 필요한 경우가 아니라면 $()보다는 자바스크립트로 사용하는게 더 빠르다.

  // 속도비교 예시
  $(this).attr('id'); 보다는 this.id가 더 빠름
  $.fn.method() 보다 $.method()가 더 빠름
  $.data() 보다 .data()가 더 빠름

  // Bad
  $('a').bind('click', function () {
      console.log('You clicked: ' + $(this).attr('id'));
  });
  
  // Good
  $('a').bind('click', function () {
      console.log('You clicked: ' + this.id); // this는 a태그가 만든 DOM 객체
  });

TOP

목록 게시안함 삭제 수정