Rails 4: How to add an external javascript file from another site on a specific page

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

<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 this:

 //= 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 another site, for example. http://otherdomain.com/xyz.js on the page of the special site of my site. Suppose I want to add this external js file ONLY to the page with the description http://mysite.com/profile And I want to add this js file ONLY to the title of the page. So, how can I do this? Please, it is not recommended to save this external file locally, as this is not an option for me.

+6
source share
3 answers

Add a content block to your layout:

layout.html.erb

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

In one template that requires a JS file, output it to this block:

profile.html.erb

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

As cool as turbolines, I find myself with a bigger headache than before they existed. I also add page specific css or js in certain special circumstances that it exists in the header. It may be hacked, but I put it in a conditional layout using current_page? assistant

  = javascript_include_tag "whatever.com/external.js" if ( current_page?(:controller => "users" ) && current_page?(:action => "index" ) ) 
+4
source

I am currently considering a solution to dynamically embed a script :

 (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)); 
+2
source

Source: https://habr.com/ru/post/954023/


All Articles