jquery/JS positioning
I'm going to confess I don't know what's best.
Normally, I place the jquery library in the head of a webpage. I do the same thing for any jquery plugins or javascript functions.
What I'm curious about is where to place the selectors. At the bottom, before the end body tag. Or before the site code.
Example:
<div id="somediv">stuff inside</div>
<script language="javascript" type="text/javascript">
$(function (){
$("#somediv").hide();
});
</script>
As you can see I place the selector below the html. I've seen it both ways, but I'm curious if there's a best way. And would that also be开发者_高级运维 true for all javascript related functions and plugins.
The reason I as is because sometimes IE complains about placement. While other browsers seem more forgiving, or don't care.
If you place your selectors inside:
$(function() {
// my DOM selection
});
...then it won't matter since that is a shortcut for a call to jQuery's .ready()
method which ensures that the DOM elements are loaded before the code inside runs.
If your code is positioned after the elements, then you can do without .ready()
.
Another option is to place your code in a window.onload
handler. The downside to this is that it will need to wait for all content, including images, to load before it runs. Probably not what is desired.
Either way works if you have it inside a document.ready
handler, like you already have with $(function (){ ... });
. Without the wrapper, you have to place it after the elements, e.g. at the end of the <body>
.
In either case, be sure the <script>
block occurs after jQuery (and any plugins that code needs) are included.
Both will work fine but if your page becomes complex it may seem to load slowly and appear sluggish; so if variable scoping isn't a problem you may consider placing scripts at the bottom of your pages, which would mean importing jQuery followed by firing off the rest of your scripts within $(function() { })
精彩评论