Question

In my rails app, I tried to load CSS into my view like this :

<link src="assets/stylesheets/myStyleSheet.css" type="text/css" rel="stylesheet">

and it works.

BUT When I tried to load a JavaScript file as below,

<script src="assets/javascripts/libs/modernizr-2.6.2.min.js" type="text/javascript"></script>

I am getting a 404 error (Same error for some images also)

All my files are in the right place, so does anybody have an idea to solve it?

Thanks.

Était-ce utile?

La solution

You should better use asset pipeline to include js and css files into your application.

For current example, put into your app/assets/javascripts/application.js

//= require ./libs/modernizr-2.6.2

In your app/assets/stylesheets/application.css.scss

/*
 *= require ./myStyleSheet
*/

And into your .html.erb file (e.g. application.html.erb, in <head> section)

<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>

Autres conseils

put a slash '/' before assets in the start of the src. and also css file should be included with link href not with src though it will work but not a good practice.

<link href="/assets/css_file_path.css" media="screen" rel="stylesheet" />
<script src="/assets/path_to_js_file.js"></script>

Please add a custom path to the asset pipeline in the below file:

 # config/application.rb
 config.assets.paths << Rails.root.join("app", "assets", "javascripts", "libs")

Then, in your JavaScript manifest file (mostly application.js), require the js file in order to take it when doing pre-compilation:

//= require modernizr-2.6.2.min

In your CSS manifest file (mostly application.css.sass), add the below line:

/*
 *= require myStyleSheet
*/

If you have any individual external JavaScript file to include, you can add them to the precompile array in config/application.rb:

config.assets.precompile += ['custom.min.js']

If you want to see the assets loaded through the asset path, you can use this in the console:

Rails.application.config.assets.paths

Hope this could be the best option to use. :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top