Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - Is $(document).ready necessary?

Tags:

jquery

I am reading an online tutorial that says if the <script></script> is right on top of </body> the $(document).ready is not necessary b/c the document has been loaded at that moment.

Q1> Is that true?

Q2>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script src="jquery.viewport.min.js"></script>

<script>
$(window).scroll(function() { // this line will track all mouse scroll event

});
</script>

What does the $(window) mean? Is this a jquery selector? If it is, then the previous claim looks correct because we don't have to include this inside

$(document).ready(function() {

});

Q3> why we use $link here? why we choose to use $link rather than var link?

<script>
$(window).scroll(function() {
  $link = $('nav a[hash=#first]');
  $link.addClass('selected');
});
</script>

Thank you

like image 536
q0987 Avatar asked Aug 20 '10 04:08

q0987


2 Answers

Q1. Yes and no. Perhaps jQuery will still do a few things after the has been reached, but if you are just trying to find a element that was loaded previously in the body it will work.

Q2. It creates a jQuery Object pointing to the window. It is not a jQuery Selector, neither is $(document) or $(document.body) - in these you are passing a node to jQuery and not a Selector.

Q3. It caches it. By performing $link = $('nav a[hash=#first]'); we cache/assign the result to $link, as if we did $('nav a[hash=#first]') twice, then jQuery would have to find that result twice - this could become/will become quite intensive if all your calls are not cached. You should also be using var $link = $('nav a[hash=#first]');, to ensure that $link is not defined globally - as that is bad (due to variable conflicts).

As a general practice; anything which uses DOM elements should be after document ready (to ensure they have loaded and jQuery is ready to use them), anything that doesn't shouldn't (as there is no need for the wait).

like image 132
balupton Avatar answered Oct 05 '22 01:10

balupton


That's not correct. It would be correct if it was AFTER the body. You can take a look at this for more info and methods http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/

like image 45
Matt Williamson Avatar answered Oct 05 '22 03:10

Matt Williamson