Where do you store it?
Now that our script is in the right place, we have to figure out how to reference it within a view.
How do you reference it?
In your view (HAML, HTML, or otherwise), you can use JQuery’s getScript() function to retrieve the script. This, of course, requires that you have a reference to JQuery in your project.
In a view (app/views/bar.html.haml, for example), you can embed a call to the getScript() function to grab foo.js.coffee as follows:
What’s really awesome about getScript() is that there’s a handler that can be defined when the script is successfully retrieved! In the code above, we’re defining an anonymous function that prints to the console indicating that the file was found.
It’s really important to define what happens when the file is successfully retrieved. Let’s say you’re defining some objects in foo.js. If you try to use those objects while the file is asynchronously being fetched (i.e., not using the handler and just writing operations after the call to getScript()), you’ll run into errors. Hence, you can be sure that any objects in foo.js exist by waiting for the file to be fetched and then carrying on with your operations.
Hope it helps!