code

jQuery의 document.ready 함수는 언제 사용해야합니까?

codestyles 2020. 8. 13. 23:23
반응형

jQuery의 document.ready 함수는 언제 사용해야합니까?


Javascript / jQuery를 처음 사용하기 시작했을 때 document.ready를 사용하라는 지시를 받았지만 실제로 그 이유를 배우지 못했습니다.

누군가 jQuery 내부에 javascript / jquery 코드를 래핑하는 것이 합리적 일 때에 대한 몇 가지 기본 지침을 제공 할 수 document.ready있습니까?

내가 관심있는 몇 가지 주제 :

  1. jQuery의 .on()방법 : .on()AJAX에 대한 방법을 꽤 많이 사용합니다 (일반적으로 동적으로 생성 된 DOM 요소에서). 해야 .on()클릭 핸들러는 항상안에 document.ready ?
  2. 성능 : document.ready 내부 또는 외부에 다양한 javascript / jQuery 객체를 유지하는 것이 더 성능이 좋습니까 (또한 성능 차이가 중요합니까?)?
  3. 객체 범위 : AJAX로로드 된 페이지는 이전 페이지의 document.ready 안에 있던 객체에 액세스 할 수 없습니다 . 맞습니까? document.ready 외부에 있는 객체 (즉, 진정한 "전역"객체) 에만 액세스 할 수 있습니까?

업데이트 : 모범 사례를 따르기 위해 모든 자바 스크립트 (jQuery 라이브러리 및 앱 코드)가 내 HTML 페이지 하단defer 에 있으며 AJAX로드 페이지의 jQuery 포함 스크립트에 있는 속성을 사용하여 이 페이지에서 jQuery 라이브러리에 액세스 할 수 있습니다.


간단히 말해서

$(document).readydocument준비 되면 시작되는 이벤트입니다 .

head섹션에 jQuery 코드를 배치 하고 dom요소 (앵커, img 등) 에 액세스하려고 한다고 가정 하면는 html위에서 아래로 해석되고 jQuery 코드가있을 때 html 요소가 없기 때문에 액세스 할 수 없습니다. 실행합니다.

이 문제를 극복하기 위해 $(document).ready모든 dom요소에 액세스 할 수있을 때 호출되는 함수 내에 모든 jQuery / javascript 코드 (DOM을 사용)를 배치 합니다 .

당신이 (직전, 모든 DOM 요소 후 하단에 jQuery 코드를 배치 할 때 그리고 이것은 이유이다 </body>), 필요에 대한이 없다$(document).ready

위에서 설명한 것과 같은 이유로 메소드 를 사용 하는 경우에만 on메소드를 내부 에 넣을 필요가 없습니다 .$(document).readyondocument

    //No need to be put inside $(document).ready
    $(document).on('click','a',function () {
    })

    // Need to be put inside $(document).ready if placed inside <head></head>
    $('.container').on('click','a',function () {
    });

편집하다

댓글에서

  1. $(document).ready이미지 나 스크립트를 기다리지 않습니다. 사이의 큰 차이 그게 전부 $(document).ready$(document).load

  2. DOM에 액세스하는 코드 만 준비 처리기에 있어야합니다. 플러그인 인 경우 준비 이벤트에 있으면 안됩니다.


답변:

jQuery의 .on () 메서드 : AJAX에 대해 .on () 메서드를 꽤 많이 사용합니다 (DOM 요소를 동적으로 생성). .on () 클릭 핸들러는 항상 document.ready 안에 있어야합니까?

아니요, 항상 그런 것은 아닙니다. 문서 헤드에 JS를로드하는 경우 필요합니다. AJAX를 통해 페이지가로드 된 후 요소를 생성하는 경우에는 그렇게해야합니다. 스크립트가 html 요소 아래에 있으면 핸들러도 추가 할 필요가 없습니다.

성능 : document.ready 내부 또는 외부에 다양한 javascript / jQuery 객체를 유지하는 것이 더 성능이 좋습니까 (또한 성능 차이가 중요합니까?)?

때에 따라 다르지. 핸들러를 연결하는데도 같은 시간이 걸리며, 페이지가로드되는 즉시 발생하는지 또는 전체 문서가로드 될 때까지 기다리 려는지 여부에 따라 다릅니다. 따라서 페이지에서 수행중인 다른 작업에 따라 달라집니다.

객체 범위 : AJAX로로드 된 페이지는 이전 페이지의 document.ready 안에 있던 객체에 액세스 할 수 없습니다. 맞습니까? document.ready 외부에있는 객체 (즉, 진정한 "전역"객체)에만 액세스 할 수 있습니까?

본질적으로 자체 함수이므로 전역 범위 (모든 함수 외부 / 위)에서 선언 된 vars에만 액세스 할 수 있습니다. window.myvarname = '';


jQuery를 안전하게 사용하기 전에 페이지가 조작 할 준비가 된 상태인지 확인해야합니다 . jQuery를 사용하면 코드를 함수에 넣은 다음 해당 함수를 $(document).ready(). 우리가 전달하는 함수익명의 함수일 수 있습니다.

$(document).ready(function() {  
    console.log('ready!');  
});

문서가 준비되면 .ready ()에 전달하는 함수가 실행됩니다. 여기서 무슨 일이 일어나고 있습니까? $ (document)를 사용하여 페이지의 문서에서 jQuery 객체를 만든 다음 해당 객체에 대해 .ready () 함수를 호출하여 실행하려는 함수를 전달합니다.

이것은 당신이 많이하는 일이기 때문에 당신이 선호한다면 이것에 대한 속기 방법이 있습니다. $ () 함수는 당신이 함수를 전달한다면 $ (document) .ready ()에 대한 별칭으로서 이중 역할을합니다 :

$(function() {  
    console.log('ready!');  
});  

이것은 좋은 읽기입니다 : Jquery Fundamentals


.ready ()-DOM 이 완전히로드되었을 때 실행할 함수를 지정합니다.

$(document).ready(function() {
  // Handler for .ready() called.
});

다음은 모든 jQuery 메서드 목록입니다.

$ (document) .ready () 소개 읽기


To be realistic, document.ready is not needed for anything else than manipulating the DOM accurately and it's not always needed or the best option. What I mean is that when you develop a large jQuery plugin for example you hardly use it throughout the code because you're trying to keep it DRY, so you abstract as much as possible in methods that manipulate the DOM but are meant to be invoked later on. When all your code is tightly integrated the only method exposed in document.ready is usually init where all the DOM magic happens. Hope this answers your question.


You should bind all actions in document.ready, because you should wait till the document is fully loaded.

But, you should create functions for all actions and call them from within the document.ready. When you create functions (your global objects), call them whenever you want. So once your new data is loaded and new elements created, call those functions again.

These functions are the ones where you've bound the events and action items.

$(document).ready(function(){
bindelement1();
bindelement2();
});

function bindelement1(){
$('el1').on('click',function...);
//you might make an ajax call here, then under complete of the AJAX, call this function or any other function again
}

function bindelement2(){
$('el2').on('click',function...);
}

I appended a link to a div and wanted to do some tasks on the click. I added the code below the appended element in the DOM but it did not work. Here is the code:

<div id="advance-search">
   Some other DOM elements
   <!-- Here I wanted to apppend the link as <a href="javascript:;" id="reset-adv-srch"><span class="bold">x</span> Clear all</a>-->
</div>

<script>
  $("#advance-search #reset-adv-srch").on("click", function (){
     alert('Link Clicked');``
  });
</script>

It did not work. Then I placed the jQuery code inside $(document).ready and it worked perfectly. Here it is.

$(document).ready(function(e) {
    $("#advance-search #reset-adv-srch").on("click", function (){
        alert('Link Clicked');
    });
});

he ready event occurs when the DOM (document object model) has been loaded.

Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.

The ready() method specifies what happens when a ready event occurs.

Tip: The ready() method should not be used together with .

참고URL : https://stackoverflow.com/questions/13062246/when-should-i-use-jquerys-document-ready-function

반응형