1

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.

Dan Klos
  • 699
  • 7
  • 21
  • Any chance the path to your image in JS file needs to use the [main HTML file location as root](http://stackoverflow.com/questions/2188218/relative-paths-in-javascript-in-an-external-file), whereas the path in CSS file is [relative to that CSS file](http://stackoverflow.com/questions/5815452/how-to-use-relative-absolute-paths-in-css-urls)? I.e. is your issue still there if you use absolute path? – ghybs Nov 12 '15 at 16:54
  • You cannot use the original path in css actually. When you use something like `background: image-url('image.png')`, sprockets will add the fingerprint to it (in production only) – Yury Lebedev Nov 12 '15 at 17:05
  • @ghybs I just tried that, does not work, but a good idea. – Dan Klos Nov 12 '15 at 17:16
  • @YuryLebedev Ah! So then is there a way to get sprockets to fingerprint the path or link to the fingerprinted path in a JS file? – Dan Klos Nov 12 '15 at 17:16
  • @DanKlos i will write a short answer with the options a know – Yury Lebedev Nov 12 '15 at 17:17

1 Answers1

1

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

Yury Lebedev
  • 3,985
  • 19
  • 26