整理 jQuery
我有一个页面使用了大量 jQuery 代码,但它变得难以管理。我希望能够对其进行整理,将相关部分放入单独的 .js 文件中,并将它们包含在页面的脚本标记中。
我似乎可以通过将它们创建为 jQuery 插件,然后在页面上使用 $(document).plugin_name(); 来做到这一点。
可以这样做还是有更好/更简单的方法?
谢谢
I have a page which uses a lot of jQuery code but it is becoming unmanageable. I want to be able to tidy it up to place related parts into separate .js files and include them onto the page in a script tag.
I seem to be able to do this by creating them as jQuery plugins then by using $(document).plugin_name(); on the page.
Is it okay to do this or is there a better/easier way?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不必做任何这样的恶作剧,如果您以正确的顺序导入 .js 文件,它将像全部在一个文件中一样工作。您还可以在任何文件中使用
$(document).ready(function() { });
块,不会出现任何问题。You don't have to do any such shenanigans, if you import the .js files in correct order, it will work like it was all in one file. You can also use
$(document).ready(function() { });
block in any file without problems.我建议您尝试一下 Sprockets:http://getsprockets.org/。它允许您将 Javascript 分成各种可管理的文件,并将它们组合成一个文件进行部署。
对于大型应用程序来说,在开发时必须将 Javascript 拆分为多个文件,但将它们合并为一个文件对于管理生产中加载时的延迟非常重要。
I suggest you try out Sprockets: http://getsprockets.org/. It allows you to separate your Javascript into various manageable files, and have them combined into one file for deployment.
Having Javascript split into multiple files is a must for large applications at development time, but having them combined into one is very important for managing latency at load time in production.
尝试查看 Rebecca Murphey 的帖子,了解组织您的代码
如果您使用 jQuery UI,它有一个非常酷的小部件制作工具,可以帮助您创建自己的 有状态插件
Try checking out Rebecca Murphey's post about organizing your code
If you're using jQuery UI its got a very cool widget maker tool that helps you to create your own stateful plugins