Rails 4: How to add external javascript file from other site in a specific page
Solution 1
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 %>
Solution 2
As cool as turbolinks are, I find myself with more headaches than before they existed. I also inject page specific css or js in certain special circumstances it exists in the header. It might be hacky, but I put it in the layout with a condition using the current_page? helper
= javascript_include_tag "whatever.com/external.js" if ( current_page?(:controller => "users" ) && current_page?(:action => "index" ) )
Solution 3
A solution I'm looking at presently is injecting the script dynamically:
(function(d, script) { script = d.createElement('script'); script.type = 'text/javascript'; script.async = true; script.onload = function(){ // remote script has loaded }; script.src = 'http://www.google-analytics.com/ga.js'; d.getElementsByTagName('head')[0].appendChild(script); }(document));
JVK
Updated on June 19, 2022Comments
-
JVK almost 2 years
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.
-
JVK over 10 yearstrh, I have thought about that, but that is last hacky option and I will do that once there is no better option. Thanks anyway
-
streetlogics over 8 yearsIs this
<% if content_for?(:header) %>
part actually needed? In this instance, yielding:header
if there is no content will yield an output of nothing, effectively leaving a blank line just like this code does. Seems like just going with<%= yield(:header) %>
is the way to go. -
Ross Allen over 8 yearsMy answer is from 2 years ago, so I can't remember why I added the conditional. I agree though, it's unnecessary. I'll update the answer. Thanks for the tip.