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
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).
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With