Dev./javascript

[jQuery] best practice - jQuery Ready Event

인쥭 2021. 2. 16. 13:37
반응형

이 글은 아래 사이트를 토대로 작성되었습니다.

 

jQuery Best Practices

jQuery Best Practices Greg Franko About the Speaker JavaScript Engineer at AddThis (We are hiring) Open Source Enthusiast Soon-to-be Author Hates the word HTML5 Contact Details Github: https://github.com/gfranko Twitter: https://twitter.com/GregFranko Link

gregfranko.com

 

jQuery Ready 이벤트

i). 일반적인 경우

$("document").ready(function() {
  // DOM이 준비됨
  // 이후의 코드는 여기에 작성됨
});

또는

$(function() {
  // DOM이 준비됨
  // 이후의 코드는 여기에 작성됨
});

 

ii). better practice

(function($, window, document) {

  // 이후 $는 local scope로 사용됨

 // 문서에서 jQuery ready 이벤트를 대기(Listen)
 $(function() {

   // DOM이 준비됨

 });

 // 이후의 코드는 여기에 작성됨

}(window.jQuery, window, document));
// global jQuery 오브젝트가 변수로 전달됨
  • 위 함수는 즉시실행함수의 형식을 따옴.
    • 따라서 $ (즉, jQuery 객체), window, document 등이 local scope로 맞춰지는 장점이 있다.
  • 그러나 위 코드는 코드가 길어질수록 즉시실행함수에 전달된 매개 변수인 window.jQuery, window, document를 알기 힘들어진다.
    • 스크롤을 직접 내려서 확인하는 과정이 필요하기 때문!

 

iii). best practice

(function(yourcode) {

  // global jQuery 오브젝트가 변수로 전달됨
  yourcode(window.jQuery, window, document);

}(function($, window, document) {

  // 이후 $는 local scope로 사용됨

  // 문서에서 jQuery ready 이벤트를 대기(Listen)
  $(function() {

    // DOM이 준비됨

  });

  // 이후의 코드는 여기에 작성됨
}
}));
  • 역시 즉시실행함수를 활용한 yourcode가 전달된다.
    • 함수 이름은 yourcode 가 아닌 임의의 명칭을 사용해도 좋다.
  • yourcode는 window.jQuery를 지역 변수인 $로 받아 실행된다.
  • $()의 $는 jQuery에서 사용되는 함수이다. yourcode 실행시 지역 변수인 $는 실제로 window.jQuery를 담는 일급함수로 실행되므로 성능 상의 이득이 있다.
    • 이후의 모든 $ 기호는 window.jQuery가 아닌 지역 변수로 취급되기 때문.
  • ii).의 형식을 바꾸어 매개변수에 전달된 객체를 코드의 최상단에서 즉시 알 수 있게 수정되었다.