Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Suppose that we attach a .click() handler to an anchor (<a>) tag in the $(document).ready callback. This handler will cancel the default action (following the href) and show an alert.

What I would like to know is when exactly the callback will execute and 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.

Here are different HTML pages that contain an anchor but the order of inclusion of the scripts is different. What's the difference (if any) between them? Will different browsers behave differently?

Page1:

<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> 

Page2:

<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> 

Page3:

<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> 

So is it possible that a user gets redirected to the href by clicking on the anchor and never sees the alert (ignoring the case of javascript disabled of course)? Could this happen in any of the examples I provided?

All that I need is to make sure that the click event handler has been attached to the anchor before the user has any possibility to click on this anchor. I know that I can provide an empty href and then progressively enhance it in javascript but this is a more general question.

What will happen in case that the HTML is quickly generated by the web server but the jquery library takes time to be fetched from a distant server? Will this influence my scenario? What's the order of inclusion of the scripts compared to loading the DOM? Could they be done in parallel?

like image 969
Darin Dimitrov Avatar asked Jul 10 '10 17:07

Darin Dimitrov


People also ask

When callback function is executed?

A callback function is a function that occurs after some event has occurred. The reference in memory to the callback function is usually passed to another function. This allows the other function to execute the callback when it has completed its duties by using the language-specific syntax for executing a function.

What does $( document .ready function () do?

$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

What is $( document .ready () and $( window .load () in jQuery?

ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.

What is difference between $( document .ready function () vs $( function ()?

So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.


1 Answers

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> 
like image 50
Doug Neiner Avatar answered Sep 16 '22 12:09

Doug Neiner