2012-03-19 4 views
2

이 어떻게 구문 차이 : jQuery를 기능

(function($) { 
     /// code 
})(jQuery) 

jQuery를에 $(document).ready(function() 다를?

나는 ready 기능을 알고 있습니다. 시작하기 전에 HTML이로드 될 때까지 기다립니다. 그러나 (function($)도 똑같습니까?

+1

가능한 중복 [?이 jQuery를 준비 기능의 차이점은 무엇입니까 (HTTP가 (당신이 $('selector')가 짧은, 모든 시간을 jQuery('selector') 입력 싶지 않을 것이다) jQuery에 속기 별명 $을 사용합니다 : //stackoverflow.com/questions/2662778/what-is-the-difference-between-these-jquery-ready-functions) – epascarello

답변

1

은 "속기는"단순히 $()입니다 :

//both do the same thing 
$(document).ready(function(){ 
    //run when DOM is ready 
}); 

$(function(){ 
    //run when DOM is ready 
}); 

그러나, 첫 번째 코드는 하지 .ready()과 동일합니다. 당신이해야하는 것은 immediately-invoked function expression (IIFE), 또는 평신도의 측면에서,이 함수 이름이없는이 "기능 및 통화"하지만 같은 단지 동일

//both are the same 
(function($) { 
    //run stuff here immediately! 
})(jQuery) //arguments outside wrapping parenthesis 

(function($) { 
    //run stuff here immediately! 
}(jQuery)) //arguments inside wrapping parenthesis 

"바로이 기능을 실행" (익명 함수) 및 호출 :

function functionWithNoName($){ 
    //"jQuery" in the call is "$" in here 
} 
functionWithNoName(jQuery) 

이 방법은 종종 다른 LIBR하면서 대한 jQuery $를 사용하는 코드를 보호하는 데 사용 Aries는 동일한 $ 함수 이름 thus prevent conflicts을 사용합니다.jQuery를 단지의

(function($) { 
    //run jQuery using the "$" safely in here 
}(jQuery)) 
//while some other libraries like mootools use "$" out here 
3

나는 준비 기능이 무엇인지 알고 있습니다. 시작하기 전에 HTML이로드 될 때까지 기다립니다. 그러나 (function($) { ... })()도 똑같습니까?

아니요. 컨트롤이 해당 명령문에 도달하면 즉시 실행됩니다.

$(document).ready(function() { alert('happens second'); }); 

(function($) { 
    alert('happens first'); 
})(jQuery); 

이 먼저 손을보고 실행 해보십시오.

2
(function($) { 
     /// code 
})(jQuery) 

이것은 자체 실행 익명 함수이며 자바 스크립트 인터프리터가 읽는 즉시 블록 내부의 코드를 실행합니다.

이 jQuery를 준비 동일합니다 다음 문, 혼동되지 않습니다 만 DOM 후 실행됩니다

$(function() { 
    // code 
}); 

$(document).ready(function() { 
    // code 
}); 

이 jQuery를 준비 기능은 모든 요소를로드 완료 (이미지는 상당히 걸릴 수 있습니다 느린 연결에서 오랜 시간 사용).

첫 번째와 마지막 두 개가 동일하지 않은 경우 자체 실행 기능은 jQuery 준비 기능 전에 항상 발생하며 때로는 페이지의 크기와 사용자 연결 속도에 따라 다릅니다. $(document).ready()에 대한