Вопрос

I am using morris.js to display a graph. The relevant js files are in vendor/assets/javascripts

I include them in application.js

//= require raphael
//= require morris

The graph renders correctly when I am on the page that contains the morris graph element.

Problem is that all the other pages with javascript don't work anymore (where there are no morris graph elements).

I get this error:

Error: Graph container element not found
 throw new Error("Graph container element not found");

So how would I include the js files at the end of a certain page?

I have tried to include the following at the end of the specific page:

<%= javascript_include_tag "raphael.js" %>
<%= javascript_include_tag "morris.js" %>

But because the graph needs some coffee script located in employee.js.coffee:

jQuery ->
Morris.Line
 element: 'averages_chart'
 data: $('#averages_chart').data('averages')
 xkey: 'month'
 ykeys: ['average']
 labels: ['Average']

I get the following error:

ReferenceError: Morris is not defined
return Morris.Line({

I assume this is happening because its loading the coffee script at the beginning of the page before the javascript_include_tag?

Please help

Это было полезно?

Решение

My guess is that employee.js is included in application.js and thus getting loaded, as you suggest, before morris.js. The simplest solution is to remove employee.js from application.js and include it only in the pages that use it. Alternatively, wrap the code in employee.js so that its use of Morris only executes when you know morris.js has been loaded.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top