Dan Klos
Dan Klos

Reputation: 709

Image assets available to CSS files but not JS files -- why?

I'm trying to access via a js file an image in the asset pipeline, however I receive a 404 error that the image is not present. My understanding is that Rails fingerprints and precompiles/preloads the images/assets onto the browser, so the file path 'imageName.png' becomes something to the effect of 'imageName-uniqueFingerprint.png', thus making the original path no longer valid. (Correct me if I'm misunderstanding)

What I don't understand is why I can use the original path in a CSS file, ex: background: url('nebula_small.png') and the image is retrieved just fine, however if I attempt to use the same path in a JS file I get the 404. I thought everything in the Assets directory was precompiled by Rails and thus I would assume have equal access to the respective assets.

I could write a helper method (per this StackOverflow suggestion) associating the digest_path to the original path, however I'm wondering if there's some way to simply give the JS file the same access to the images that the CSS file has.

Still new to Rails so if you need clarification or I've worded this poorly, my apologies. Thank you for your time.

Upvotes: 1

Views: 182

Answers (1)

Yury Lebedev
Yury Lebedev

Reputation: 4015

I guess the easiest way to add an .erb extension to your .js file, and use the asset_path rails helper:

$('#logo').attr({ src: "<%= asset_path('logo.png') %>" });

The second way, which is a bit more complex, would be to parse your .sprockets-manifest-md5hash.json file, which is compiled to your public folder, and which contains all the urls to your images. You can read more about it here:

http://edgeguides.rubyonrails.org/asset_pipeline.html#precompiling-assets

https://github.com/rails/sprockets/blob/master/UPGRADING.md#publicassetsmanifest-abc123json-location

Upvotes: 1

Related Questions