If you know what require.js does and Ruby on Rails is your thing, then you have come to the right place. If not, I encourage you to read up on following topics:
- Modular approach to writing JavaScript
- AMD and JavaScript
- Dependency management, Module Loading, and Lazy Loading
Installation and Setup
- Add ‘requirejs-rails’ gem in the Gemfile of your project. It relieves you from some manual labour.
- Get rid of everything from your application.js which is located under /assets/javascripts/application.js
- Now locate your application layout under views/layouts/application.html.erb
- Replace yourwith
- Do ‘Bundle Install’ and Restart rails server. When your server is back up and running, view page source and you should see following in your HEAD
-
<script data-main="application" src="/assets/require.js"></script>
- Open application.js
- Paste the following code in it
Start writing your modules
Let’s say you need an Ajax loader for your Ajax requests and you wish to write a separate module for it. Great idea. Now, let me tell you how you can write a module that can be loaded with require.js. In other words, this module that we are about to write will comply to AMD (Asynchronous module definition)Basic module syntax:
ajaxloader.js You define a module by using ‘define’ and it usually takes 2 arguments 1st of which is an array of its dependencies and 2nd is an anonymous function. You can either return a value, another function or an object literal as above.Basic module with dependencies:
Let’s say our ajax loader module depends on jQuery. jQuery needs to be passed as a reference. Like this You must wonder, how does ‘define’ find dependencies? Well, we need to tell require.js about the location where it can find modules, dependencies. Configure require.js- Open your application.js and let’s add jQuery as your dependency.
Syntax:
There’s a lot of configuration options available at http://requirejs.org/docs/api.html#config however, for now, we shall focus on setting jQuery as a dependency (jQuery is AMD compatible unlike Backbone, underscore, and many other popular libraries, however, SHIM config can help you our in that regard http://requirejs.org/docs/api.html#config-shim).Explanation:
Now it’s time to tell require.js about our ajax loader module. Follow the steps below- Add the following code in application.js right below require.config chunk of code
- require.js
- application.js
- jquery.min
- ajaxloader.js (Loaded after jQuery because it depended on jQuery)
- Abstract your code without polluting the global namespace by using AMD pattern in your modules.
- Manage Dependencies in a much more structured way.
- Lazy load your modules.
- Optimize your modules