Rails 4: How to add external javascript file from other site in a specific page

JVK picture JVK · Sep 17, 2013 · Viewed 10.7k times · Source

I am using turbolink (rails4) and following js link gets generated by application.js file in my pages header section

<script data-turbolinks-track="true" src="/assets/jquery.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/jquery_ujs.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/turbolinks.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/global.js?body=1"></script>

My application.js looks something like:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require bootstrap.min.js
//= require respond.min.js

I want to add an external javascript file from OTHER site e.g. http://otherdomain.com/xyz.js in a specifc page of my site. Suppose I want to add this external js file ONLY in a specifc page http://mysite.com/profile And I want to add this js file ONLY in header part of the page. So how can I do that? Please don't suggest to save that external file locally as that is not an option for me.

Answer

Ross Allen picture Ross Allen · Sep 20, 2013

Add a content block in your layout:

layout.html.erb:

...
<head>
  <%= yield(:header) %>
</head>
...

In the one template that requires the JS file, render it into that block:

profile.html.erb:

<% content_for(:header) do %>
  <script src="http://otherdomain.com/xyz.js"></script>
<% end %>