简体   繁体   English

Ruby on Rails 4:如何包含Javascript和CSS?

[英]Ruby on Rails 4: How to include Javascript and CSS?

I'm new to rails and I'm building an application using rails 4. I want to create a page that uses JQuery, another 3rd party javascript library available via CDN, a 3rd party CSS library available via CDN, my own javascript, and my own CSS. 我是Rails的新手,正在使用Rails 4构建应用程序。我想创建一个页面,该页面使用JQuery,可通过CDN获得的另一个第三方JavaScript库,可通过CDN获得的第三者CSS库,我自己的javascript和我自己的CSS。 I need to use the: 我需要使用:

jQuery(function($) {
  ...
});

function to execute some javascript when the page is loaded and this only seems to work if I put the call to jQuery(function($)... in the of the document. 加载页面时执行一些javascript的函数,并且这似乎仅在我将jQuery(function($)...的调用放在文档的中时才起作用。

I want JQuery to be included in all my apps pages, but everything else I mentioned above I only want included in this particular page. 我希望将JQuery包含在我的所有应用程序页面中,但是我上面提到的所有其他内容都只希望包含在此特定页面中。

What should I do? 我该怎么办? I've been reading various things online and I'm feeling confused. 我一直在网上阅读各种内容,感到困惑。 Should I download the 3rd party resources and include them somewhere under the vendor directory? 我应该下载第三方资源并将其包含在供应商目录下吗? If I do that, how I can I make sure they're only included in that particular page? 如果这样做,我如何确保它们仅包含在该特定页面中? Isn't downloading 3rd party resources all about leveraging the asset pipeline to combine everything into one huge JS file so there are less HTTP requests? 下载第三方资源不是有关利用资产管道将所有内容组合到一个巨大的JS文件中,从而减少HTTP请求的全部吗? So, if I only want this 3rd party script included in one page, why would I want to leverage the asset pipeline? 因此,如果我只希望将此第三方脚本包含在一页中,为什么还要利用资产管道? Should I still want to? 我还应该吗? Should I not want to have page specific javascript files? 我是否不应该具有页面特定的javascript文件? If so, how about the javascript that needs to be called to initialize that particular page (eg in order to allow for unobtrusive javascript) and shouldn't be called anywhere else? 如果是这样,那么需要调用该javascript来初始化该特定页面的Java怎么样(例如,为了允许使用兼容的javascript),并且不应在其他任何地方调用它?

Where do the javascript and css files that I have written go? 我写的javascript和CSS文件在哪里? How do I make sure they get included in the head of the document? 如何确保它们包含在文档的开头? Do I need to add a yield block in the head of my application layout in order to get this to happen 我是否需要在我的应用程序布局的开头添加一个yield块,以使这种情况发生

Someone please help me to learn the standard and best-practices way of doing this. 有人请帮助我学习执行此操作的标准方法和最佳实践。

您可以通过将它添加到application.js来创建common.js并将其包含在资产管道中,此外,如果您不使用require_tree ,则必须使用jQuery(function($)分别包含文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM