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

Example 3 will have the highest chance of the user being able to click on the link without the handler having attached itself yet. Since you are loading the jQuery library after the link is rendered, if Google’s servers are a little slow (or the DNS lookup takes a second or so), or the users computer is slow to process jQuery, the link will not have its click handler attached when the user tries to click it.

Another situation where this might happen is if you have a very large or slow loading page and this link is at the top. Then the DOM may not be fully ready when parts of it are visible. If you are running into a problem like this, the safest thing to do is:

  1. Load jQuery in the head (example 1 or 2)
  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>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)