2

I have an external javascript plugin and there is a lot of code like this where the image src attribute is built dynamically.

$prod.append("<img class='fx_shadow' id='shd_" + i + "' + src='" + folderAssets + "/shadow_fx.png' />");

With rails 4.1+, I am precompiling the related images and assets that this external code provides and references above. Naturally, the images fail to load in production because using direct src attributes doesn't capture the fingerprint of the digested and precompiled image.

How do I call the asset_url method (which does output the correct asset file name with the digest) properly from an external javascript file rather than a css file? (This javascript is not a restful template js.erb file, but rather, a js file included in the manifest.)

Also, is there an elegant way to approach and refactor this?

4
  • What's the file's extension you have for your JavaScript is it .js or .js.erb? Commented Nov 3, 2014 at 11:19
  • js. I should change it to use js.erb? Commented Nov 3, 2014 at 11:23
  • 1
    Yes, change it to .js.erb and then: $prod.append("<img class='fx_shadow' id='shd_" + i + "' + src='<%= asset_path('shadow_fx.png') %>' />"); Commented Nov 3, 2014 at 11:25
  • 1
    I am not if this will work, but also try doing this: $prod.append("<%= image_tag 'shadow_fx.png', :class => 'fx_shadow' %>"); Commented Nov 3, 2014 at 11:28

2 Answers 2

4

Solution 1

Add a function

function imagePath(image){
    return "http://" + window.location.host + "/assets/"+ image;
}

$prod.append("<img class='fx_shadow' id='shd_" + i + "' + src=imagePath(image) />");

Solution 2

Change the file from js to js.erb

$prod.append("<img class='fx_shadow' id='shd_" + i + "' + src='<%= asset_path('shadow_fx.png') %>' />");
Sign up to request clarification or add additional context in comments.

Comments

3

Checkout 2.3.3 JavaScript/CoffeeScript and ERB. You need to change .js to .js.erb extension, for example: javascript_filename.js.erb. Then you can use it like so:

$prod.append("<img class='fx_shadow' id='shd_" + i + "' + src='<%= asset_path('shadow_fx.png') %>' />");

or:

var image = $("<%= image_tag 'shadow_fx.png', :class => 'fx_shadow' %>");
image.attr('id', 'shd_'+i);
$prod.append(image);

In second option, you have to make image_tag as image element and then add id attribute to it because i is a JavaScript variable, that's why it has to be added in a separate line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.