Skip to content

Instantly share code, notes, and snippets.

@johnib
Last active September 19, 2016 20:08
Show Gist options
  • Save johnib/5875b336c3ea759eb61fdb2ed811b56b to your computer and use it in GitHub Desktop.
Save johnib/5875b336c3ea759eb61fdb2ed811b56b to your computer and use it in GitHub Desktop.
RequireJS explained
<!DOCTYPE html>
<html lang="en">
<head>
<title>Require.js Multipage Demo: About</title>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container"></div>
</div>
<script src="./js/vendor/require.js"></script>
<script type="text/javascript">
// First load the configuration that tells RequireJS what is the root path to
// load modules from, define aliases, and wrap shims.
require(['./js/common'], function () {
// only then, it is possible to successfully load the application.
require(['app/main-about']);
});
</script>
</body>
</html>
<!--
1. The syntax:
require([], callback);
is used when you want to make actions, such as loading another module, ONLY after the depended module was loaded.
This is what we called "synchronous" require -- and this is bad expression.
When you say about some operation that is synchronous you mean it is like blocking operation.
This is not the case, the fetch operation goes to background and the callback is triggered upon finish.
2. In our case, we fetch the require.config.js file using a <script> tag.
Browsers fetch all scripts in parallel BUT execute them serialy, that's what makes our way to work.
-->
/**
* This is the first module that is loaded, is it bug-free?
* Would jquery ($) be usable?
*
* As this is the first module to load, and since it makes a use of its dependencies right a way,
* Shouldn't the first line be:
* define(['jquery'], function ($) { // code });
* ?
*/
define(function (require) {
var $ = require('jquery');
require('bootstrap');
$(function () {
$('h1').html(model.getTitle());
// some other jquery code
});
});
/**
* baseUrl - the root path for which each module's path will be concatenated to.
*
* paths - define an alias for a module, and require it using the alias instead the full path.
*
* shim - bootstrap is not written in RequireJS form, so in order to be able to "require" it,
* RequireJs needs to wrap it in a requirejsy module. Since each module can depend on other modules
* there needs to be a way to define dependencies on the shim.
*/
requirejs.config({
baseUrl: './js',
paths: {
'jquery': 'vendor/jquery',
'bootstrap': 'vendor/bootstrap'
},
shim: {
'bootstrap': ['jquery']
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment