Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include javascript file at the very bottom of a page

I have a Rails application. There is also a javascript (javascript1.js) file that must be include at the very bottom of each view. I put it into /assets/javascripts folder. Application.js contains the following code

//= require jquery
//= require jquery_ujs
//= some other files

//= require_directory . 

Even if don't include javascript1.js in Application.js, it will be automatically included, won't it?

So how can I do what I want?

like image 586
Alan Coromano Avatar asked Dec 23 '12 09:12

Alan Coromano


1 Answers

Separate definition, inclusion and execution of your javascript.

Here's what I would do:

  • Wrap your code in javascript1.js in a function. Now it doesn't matter when the javascript file is interpreted, as interpreting that file just adds a function for later use
  • Add a 'javascript_footer' view to the layout (via e.g. a render call or a javascript_include_tag), which is then automatically included in every view
  • In that footer, call the function defined in javascript1.js.

In response to the first comment:

Sure, you can can skip steps 1 and 3 and add the javascript to your layouts/application.html.erb using e.g.

<%= javascript_include_tag "javascript1" %> 

(assuming you are using erb templating and assuming the file is in a location where the javascript_include_tag method will automatically find it (see http://guides.rubyonrails.org/layouts_and_rendering.html).

In response to the second comment:

True, my response to your first comment does not address that. There is no simple way to exclude files from the asset pipeline, as the manifest file explicitly lists what to include. A solution is to move everything except for javascript1.js to assets/javascripts/all and change //= require_directory . to //= require_directory all. Another, ugly but pragmatic solution is to add //= require_self at the bottom and add the contents of javascript1.js to the application.js

like image 144
Confusion Avatar answered Sep 30 '22 10:09

Confusion