如何管理 Rails 3.1 中的资产?

发布于 2024-11-09 01:40:44 字数 516 浏览 0 评论 0原文

好的,我正在使用 Rails 3.1 开始一个新项目,并且我是 CoffeeScript 的新手。

无论如何,我喜欢使用代表控制器的资源文件的想法,但是如果我只想在调用控制器时渲染 JS,该怎么办?

例如,我有一个名为 Game 的控制器。在我的 games.js.coffee 文件中,我在其中放置了一些代码,每个页面请求都会调用它。即使是与游戏无关的页面。

Rails 3.0.7 中,我要做的是将 yield(:js) 放入应用程序 erb 文件中,然后调用 content_for(:js) code> 在我的 Games#action 视图中。这样,仅加载该控制器所需的 js。

或者,我处理这个问题的方式是错误的吗?为每个页面请求加载并缓存 ALL js 代码以提高性能是否更好?

感谢您的任何建议。

OK, so I'm starting a new project using Rails 3.1 and I'm new to CoffeeScript.

Anyway, I like the idea of having asset files representing controllers but what if I only want the JS to render when the controller is called?

For example, I have a controller called Game. In my games.js.coffee file, I put some code in there and it's called for every page request. Even pages that have nothing to do with Games.

In Rails 3.0.7, what I would do is put a yield(:js) in the application erb file and then call content_for(:js) in my Games#action view. That way, only the js that was needed for that controller was loaded.

Or, am I going about this the wrong way? Is it better to have ALL js code loaded and cached for every page request to improve performance?

Thanks for any suggestions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花想c 2024-11-16 01:40:44

为每个页面请求加载并缓存所有 js 代码以提高性能是否更好?

基本上,Rails 团队认为答案通常是“是”。大多数站点仅使用单个(缩小的)JS 文件即可达到最佳效果,默认情况下您在 Rails 3.1 中获得该文件。这样,一旦用户访问了站点的单个页面,所有其他页面都会快速加载,因为所有 JS 都已被缓存。

如果您的网站有大量 JS(例如 Facebook),那么我建议您将网站架构为异步加载很少使用的 JS 代码,使用像 RequireJS。否则,我不会费心在不同的控制器下加载不同的代码;这是为了获得边际效益而做的大量额外工作。

Is it better to have ALL js code loaded and cached for every page request to improve performance?

Basically, the Rails team decided that the answer is usually "yes." Most sites work best with just a single (minified) JS file, which you get by default in Rails 3.1. That way, once the user has accessed a single page of your site, all other pages will load quickly, since all the JS has been cached.

If your site has a huge amount of JS (think Facebook), then I'd suggest architecting your site to load rarely-used JS code asynchronously, using a library like RequireJS. Otherwise, I wouldn't bother loading different code under different controllers; it's a lot of extra work for a marginal benefit.

世界等同你 2024-11-16 01:40:44

看看这个插件,我认为它解决了您的问题: https://github.com/snitko/specic_assets

Take a look at this plugin, I think it solves your problem: https://github.com/snitko/specific_assets

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文