1
 <div class="actions"> <h3>Actions</h3> <ul> <li><a href="/configurations">Configurations</a></li> </ul> </div> <script type="text/javascript" src="/jquery.min.js"></script> <script type="text/javascript"> $('ul a').click(function(){ alert(""); }); </script> 

In the above code is document.ready necessary. What i mean is, is there any case when js will be executed before html

2 Answers 2

2

.ready is a shortcut to DOMContentLoaded (or onreadystatechange or an assortment of workarounds for other browsers). That event fires when the DOM has been built - in other words, when the whole HTML has been downloaded.

So, as long as your script tags are the last thing before </body> (they are not inside any divs or other elements) the end result is the same, you don't need $(document).ready. That is even recommended, since putting your scripts in the <head> will slow down the loading of content.

Though I'd recommend you to adopt this pattern, to avoid problems with the $ global:

<script> (function($){ $('ul a').click(function(){ alert("") }) })(jQuery) </script> 

These other questions are interesting reads:

Sign up to request clarification or add additional context in comments.

2 Comments

jQuery(function($) { }) is a better way of doing it. It doesn't really cost anything to use document ready here, and it'd cause confusion if you moved the code at a later date.
"better" here is subjective - the check for .ready is unnecessary. Using closures like this should be well understood by most.
-1

In your case, it seems there is no problem. But, when you use pictures (<img />), there is a possibility for the document to execute your function (it fires "ready" event) even if the pictures aren't displayed yet.

2 Comments

document.ready fires when DOM is loaded, it doesn't wait for the images to load.
You're thinking of the load event. DOMReady fires before images are loaded.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.