Skip to content

How to use require.JS?

Johan edited this page Jun 6, 2014 · 2 revisions

Prepare your JavaScript file

All require.js files must be wrapped into a require() function:

require(['jquery'], function($) {
	// my code
	$('document').ready(function() {});
});

Use require.JS in apps

Note: never precise the .js extension when you deal with require.js.

Load module from PHP

  1. Store your file in a /js/ subfolder located at the root of your app folder: /my-app/js/script.js
  2. When calling your file from the view with require, prefix it with a apps! string: $this->assign('require', 'apps!my-app/script');. The file /my-app/js/script.js will automatically be called

Load module directly from theme

You can call your file directly from the theme by modifying the JS variable require declared in header:

<script type="text/javascript">
	var require = {
		deps: ['bootstrap', 'apps!my-app/script']
	};
</script>

Use require.JS for a theme JavaScript file

  1. Wrap your file as described in the first point of this article.
  2. Modify the JS variable require declared in header as follow:
<script type="text/javascript">
	var require = {
		deps: ['bootstrap', 'themes!name-of-my-theme/js/script']
	};
</script>

require.js will automatically look for a file located at /themes/name-of-my-theme/js/script.js.

Clone this wiki locally