jquery/JS定位
我承认我不知道什么是最好的。
通常,我将 jquery 库放在网页的头部。我对任何 jquery 插件或 javascript 函数都做同样的事情。
我很好奇的是选择器放置在哪里。 在底部,结束正文标记之前。或者在站点代码之前。
示例:
<div id="somediv">stuff inside</div>
<script language="javascript" type="text/javascript">
$(function (){
$("#somediv").hide();
});
</script>
如您所见,我将选择器放置在 html 下方。我已经看到了这两种方式,但我很好奇是否有最好的方法。对于所有 javascript 相关的函数和插件来说也是如此。
我这样做的原因是因为有时 IE 会抱怨布局。而其他浏览器似乎更宽容,或者不在乎。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您将选择器放在里面:
...那么这并不重要,因为这是调用 jQuery 的快捷方式
.ready()
方法 确保在内部代码运行之前加载 DOM 元素。如果您的代码位于元素之后,那么您可以不使用
.ready()
。另一种选择是将代码放在
window.onload
处理程序。这样做的缺点是,它需要等待所有内容(包括图像)加载后才能运行。可能不是想要的。If you place your selectors inside:
...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.如果您将其放在
document.ready
处理程序中,则任何一种方法都有效,就像您已经使用$(function (){ ... });
那样。 如果没有包装器,您必须将其放置在元素之后,例如的末尾。
无论哪种情况,请确保包含
块在 jQuery(以及代码需要的任何插件)之后。
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.两者都可以正常工作,但如果您的页面变得复杂,它可能看起来加载缓慢并且显得缓慢;因此,如果变量作用域不是问题,您可以考虑将脚本放在底部您的页面,这意味着导入 jQuery,然后在 $(function() { }) 中触发其余脚本
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() { })