本文介绍了如何在一个页面上包含coffeescript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:一年后,如果我要再次这样做,我会使用curl.js而不是Rails资产管道。

a year later if I was going to do this again I'd do it with curl.js instead of Rails asset pipeline.

相关:

我在写一个应用程序并使用coffeescript以生成所有j。这就是为什么相关的问题不能做我需要的。

I'm writing an app and using coffeescript to generate all of the js. That's why the related question doesn't do what I need.

我想能够将coffeescript文件放在我的assets目录的子文件夹中,并且.coffee文件只能在一个页面上提供。该页面位于已命名的路线上

I'd like to be able to put a coffeescript file in a subfolder of my assets directory and have that .coffee file only get served up on one page. The page is on a named route

match'myNotifications'=> 'user#notifications'

最明显的做法是将.coffee文件放在 assets \\ javascripts \user\index.js.coffee 。但在阅读关于资产的文档之后,我不清楚。

The most obvious thing to do was to put the .coffee file in assets\javascripts\user\index.js.coffee. But after reading the docs about assets I'm unclear.

我读了这一行(来自):

I read this line (from http://guides.rubyonrails.org/asset_pipeline.html):

好的,所以我把页面特定的js放在 assets\javascripts \user.js.coffee 。然后我重新加载我的主页,Ctrl F5。 user.js文件仍在首页上加载。测试使用 $ - > alert'ready from users controller';当我加载首页时看到提醒。

Ok cool, so I put the page specific js in assets\javascripts\user.js.coffee. Then I reloaded my home page, Ctrl F5. The user.js file is still being loaded on the homepage. Tested with $ -> alert 'ready from users controller'; seeing that alert when I load the homepage.

Rails有一种方法可以让每页coffeescript文件只与该页一起提供?我读手册错了吗?在资源文件夹中是否有一个地方可以放置.coffee文件,它们不会被每个页面加载?

Does Rails have a way to have a per-page coffeescript file that will only be served up with that page? Am I reading the manual wrong? Is there a place in the assets folder that I can put .coffee files where they won't get loaded with every page?

更新:看起来我可能:

上午。

推荐答案

不仅仅是将文件包含在一个页面上,你可能只需要使用有条件的页面标记的逻辑。请参阅。这样,您的用户不必为特定网页提出额外的< script> 请求。

Rather than only including the file on one page, you might want to just use logic that's conditional on the page markup. See my answer to a related question. That way, your users don't have to make an additional <script> request for the particular page.

如果该页面有一个很多逻辑(例如,10K +缩小),那么是,拆分出来。正如您在对您的问题的编辑中建议的:而不是在 javascripts 目录的根目录中执行 require_tree。创建一个名为 global 的子目录,并将 application.js 的顶部从

If there's a lot of logic specific to that page (say, 10K+ minified), then yes, split it out. As you suggested in the edit to your question: Rather than doing require_tree . at the root of your javascripts directory, instead create a sub-directory called global and change the top of application.js from

require_tree .

require_tree global

然后将特定于页面的CoffeeScript文件放在根 javascripts 目录,并在该网页的模板中使用 javascript_include_tag 调用指向它。

Then put your page-specific CoffeeScript file in the root javascripts directory, and point to it with a javascript_include_tag call in that page's template.

这篇关于如何在一个页面上包含coffeescript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 00:42
查看更多