Programing

$ (document) .ready 콜백이 정확히 언제 실행됩니까?

lottogame 2020. 10. 25. 11:30
반응형

$ (document) .ready 콜백이 정확히 언제 실행됩니까?


콜백 .click()의 앵커 ( <a>) 태그에 핸들러를 연결한다고 가정합니다 $(document).ready. 이 핸들러는 기본 작업 (다음에 오는 href) 을 취소하고 경고를 표시합니다.

내가 알고 싶은 것은 정확히 콜백이 언제 실행될 것이며 사용자가 앵커를 클릭 할 수 있는지 (문서가 브라우저에 표시됨) 가능하지만 이벤트가 아직 첨부되지 않은 것입니다.

다음은 앵커를 포함하는 여러 HTML 페이지이지만 스크립트 포함 순서는 다릅니다. 그들 사이의 차이점 (있는 경우)은 무엇입니까? 브라우저마다 다르게 작동합니까?

페이지 1:

<html>
<head>
    <title>Test 1</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        $('a').click(function() {
            alert('overriding the default action');
            return false;
        });
    });
    </script>
</head>
<body>
    <a href="http://www.google.com">Test</a>
</body>
</html>

2 쪽:

<html>
<head>
    <title>Test 1</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
</head>
<body>
    <a href="http://www.google.com">Test</a>
    <script type="text/javascript">
    $(function() {
        $('a').click(function() {
            alert('overriding the default action');
            return false;
        });
    });
    </script>
</body>
</html>

페이지 3 :

<html>
<head>
    <title>Test 1</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <a href="http://www.google.com">Test</a>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        $('a').click(function() {
            alert('overriding the default action');
            return false;
        });
    });
    </script>
</body>
</html>

그렇다면 사용자가 href앵커를 클릭하여로 리디렉션되고 경고가 표시되지 않을 수 있습니까 (물론 자바 스크립트가 비활성화 된 경우 무시)? 내가 제공 한 예에서 이런 일이 발생할 수 있습니까?

필요한 것은 click사용자가이 앵커를 클릭 할 가능성이 있기 전에 이벤트 핸들러가 앵커에 연결되어 있는지 확인하는 것 입니다. 나는 빈을 제공하고 href자바 스크립트에서 점진적으로 향상시킬 수 있다는 것을 알고 있지만 이것은 더 일반적인 질문입니다.

HTML이 웹 서버에서 빠르게 생성되지만 jquery 라이브러리가 먼 서버에서 가져 오는 데 시간이 걸리는 경우 어떻게됩니까? 이것이 내 시나리오에 영향을 미칠까요? DOM을로드하는 것과 비교하여 스크립트를 포함하는 순서는 무엇입니까? 병렬로 수행 할 수 있습니까?


예제 3 처리기가 아직 연결되지 않은 상태에서도 사용자가 링크를 클릭 할 수있는 가능성가장 높습니다 . 링크가 렌더링 된 jQuery 라이브러리를로드하기 때문에 Google 서버가 약간 느리거나 (또는 ​​DNS 조회에 1 초 정도 소요됨) 사용자 컴퓨터가 jQuery를 처리하는 속도가 느리면 링크에 클릭 핸들러가 없습니다. 사용자가 클릭하려고 할 때 첨부됩니다.

이 문제가 발생할 수있는 또 다른 상황은 페이지가 매우 크거나 느리게로드되고이 링크가 맨 위에있는 경우입니다. 그러면 DOM의 일부가 표시 될 때 DOM이 완전히 준비되지 않을 수 있습니다. 이와 같은 문제가 발생 하는 경우 가장 안전한 방법 은 다음과 같습니다.

  1. head(예제 1 또는 2) 에서 jQuery로드
  2. Attach the click event immediately after the <a> element, but not in a DOMReady callback. This way it will be called immediately and will not wait for the rest of the document.

Once an element is rendered, it can be grabbed from the DOM, and subsequently jQuery can access it:

<a href="http://www.google.com">Test</a>
<script type="text/javascript>
    // No (document).ready is needed. The element is availible
    $('a').click(function() {
        alert('overriding the default action');
        return false;
    });
</script>

Additionally, building on user384915's comment, if the action is fully dependent on JavaScript, then don't even render it as part of the HTML, add it after jQuery is ready:

<script type="text/javascript">
jQuery(function($){
   $("<a />", { 
      style: "cursor: pointer", 
      click: function() {
        alert('overriding the default action');
        return false;
      },
      text: "Test"
   }).prependTo("body");
});
</script>

You have a couple of different questions here

When exactly the $(document).ready callback is executed?

It is executed as soon as the DOM is fully loaded. NOT when everything (such as images) are finished downloading like .load() would be. It is (in general) before that, basically it is when the page its self is built.

What I would like to know is when exactly the callback will execute

When it is clicked.

is it possible for the user to click on the anchor (the document has been shown in the browser) but the event hasn't been attached yet.

Yes, it is possible. But putting it in the .ready() give you the best chance that it will not. There are only 2 ways to do it to be 'more sure' that it will not. These are actually using the 'onclick' on the link its self, and putting the javascript directly after the link (and not in the .ready()) so that is executed immediately after the link is created.

Also, there is no difference between how the 2 code samples you provided will work. However, in the second one you do not need to put the code in the .ready(), because it exists after the link, it will always be executed after the link has been created. If you removed it from the .ready() it would be the first of the 2 ways I described above.

Additionally, instead of putting 'return false;' in your callback, it is better to use .preventDefault() and .stopPropagation() this will let you specify if you want to prevent the default action or stop the event from bubbling, or both.


It depends on many things. If you have chunked encoding for example it is possible that a user will get a chunk but because the document is not ready yet the the listener will not be attached.

The jQuery ready event is the DOMContentLoaded event in W3C compliant browsers (standardized in the HTML5 specification), and some alternatives of this in others (like readystate in IE).

DOMContentLoaded (MDC)

Fired at the page's Document object when parsing of the document is finished. By the time this event fires, the page's DOM is ready.

Because this happens before rendering it would be a solid assumption that a callback executed after this event will be able to prevent user interaction on a not-ready page.

But as as Peter Michaux pointed out in his article due the the differences of how browsers implement this event "a robust technique for early enlivenment is not possible across the big four browsers."

So I would say that you can't rely 100% on jQuery ready event, but most of the time it will work just fine.


In YUI, there are the methods onContentReady() and onAvailable(). unfortunately there is no equivalent to that in jQuery. However there is a plugin that was inspired by them:

http://www.thunderguy.com/semicolon/2007/08/14/elementready-jquery-plugin/

This should allow you to bind the events to the anchor before the DOM is fully loaded.


Your third example provides the greatest chance of the user clicking without the override handler having been attached. The browser generally downloads and parses each <script> before moving on to the next. You're pulling in jQuery from an external source (Google) -- which, while likely reliable, could be unavailable or slow to load. You've got both <script> blocks at the end of your document <body>, so previous areas of the page will probably already have been downloaded and rendered to screen while these last two scripts are handled. While this approach is advocated to present a responsive page load experience to the user, they could click during this uncertain period, and of course the override handler would not yet have been attached.

There's an interesting YUIblog article on scripts and load order here.


For sure it's possible to "cheat" the alert warning (even if the Javascript is enabled). Try to drag the link in the url field and you will see that it will be executed without that warning. This is especially problematic if the link is triggering the delete action.

About the document.ready callback - I have such problem too. Let me explain. We doing a project where all forms are displaying in popups (jQuery window). So when the popup is closed (for now) the page is reloaded, and I had cases when I am redirected to another screen instead of opening a new popup.

Totally agree with user384915 about putting javascript directly on the onClick event or even better to href tag.

참고URL : https://stackoverflow.com/questions/3220242/when-exactly-the-document-ready-callback-is-executed

반응형