error
Network Error...
Check your network connection and reload or refresh this page.

Use RequireJS in Your Site

<script src=”/script/Script.js”></script> ?
require(“Script”); ?

For most of the websites that you visit everyday, the JavaScript is not only a additional way to promote user experience but also a required method to let the site works as expectation. Nowadays, in such a so called “web 2.0” era, what is loaded and rendered by a browser is not a traditional document-like web-page but a modern program-like web-application. And since the HTML5 and CSS3 ( as well as other “live standands” ) became widely used in most websites form top of Alexa ranking to those personal blog (like this), it’s rare to meet a pure static site(in terms of client end). The scorces drive all of world of web is in JavaScript, our hero. However, just as the name, “JavaScript”, indicates that it’s initial goal is only provide some simple way for website to use, JavaScript is not designed for large scale application. The conflict between the autologous fault of the language nature and the raising demand of a suitable language led to various solutions. Here in this post, I would like to talk about some things about RequireJS, a JavaScript file and module loader who modulize JavaScript code snippits and load them asynchoronously in the standand browswer environment.

Basic about RequireJS

RequireJS is a method designed for modulize different part of a web application. It’s primary goal is to encourage modular code. First thing in detail it recommends is to use module ID instead of URLs for script tags. Then every file of script should be a module, a independent entity which is the core concept in RequireJS. Each module cantains some data or some reusable utilties and exports them as an API for other module to use. The RequireJS itself is responsible for fetch and arrange those modules and make them work efficiently and properly. RequireJS’ default module style is an AMD (Asynchoronous Module Defination) implementation. Besides that, RequireJS also support CommonJS specification which is a synchoronous one.

The basic of RequireJS is not very complicated. Some other things are related to detailed module content, which I’ll cover in later part of this post. For now, we can start get the RequireJS ready on our site.

Site directories and files

RequireJS itself is a standard JavaScript library. As you’ve already been familiar with, just download the library file and put it in site’s script path and then add a script tag to load it. Since RequireJS will be used to manage all other modules, you do not need to add other script tags to load them. As you may wonder how to tell the universal library to load site specific script, RequireJS trys to read the data-main attribute for the location of main module. RequireJS is aimed at simplify the redundant content of code and assuming that all of the codes are in JavaScript. Therefore, the extension of a JavaScript file ( a.k.a. .js ) will be auto appended. For example, you can add the script tag like this:

1
2
3
4
5
6
<!--
Load script async
Assuming main app is in /script/main.js
-->
<script data-main="/script/main"
src="/script/require.js" async ></script>

After that, you can add application script files in /script/ directory. First, I’d like to show you the structure of that directory after being managed by RequireJS.

1
2
3
4
5
6
7
8
9
# Generated by tree
script
├── main.js
├── require.js
├── utility
│   ├── foo.js
│   └── bar.js
└── vendor
└── jquery.js

In the directory tree, the main.js is where you set configurations for application and execute main application logic. You can specific which utility script will be used or which third-party packages will be used in main.js. Next, I will talk some more about the content of main.js.

Entry point: main.js

The file main.js showed in previous section is the entry point of your application. Generally, it is consised with configuration part and main app logic part.

Configuration of RequireJS

RequireJS will expose a global varible requirejs which provide an interface with RequireJS. You can use the method function config\ and pass-in an JavaScript object for this purpose. In this object, there are some common used config keys. Here, I’d like to use a example with detailed comments to show you those config key-value pairs. The physical directory structure of the following example are showed above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
requirejs.config({
// baseUrl is the root directory in which
// RequireJS find the modules by default
baseUrl: "/script",
// define a mapping table of module group
// the paths of them are relatived from baseUrl
// For example, you can use "lib/jquery" to refer
// to "/script/vendor/jquery.js"
path: {
"util": "utility",
"lib": "vendor"
},
// define the maximum time to wait for a module
// after the wait seconds, a timeout error will
// be raised. By default, it is 7 seconds. You
// can change it to a larger value depending your
// oriented network condition.
waitSeconds: 15,
});

For more information about the config, you can refer to the official API document

Another point I’d like to talk about here is an alternated method for config the RequireJS. As I’ve just methoded, the configurations are stored in a seperated script file. In some cases, you can put the configurations just with in the HTML file which load the RequireJS. For example, add the following script tag in HTML file:

1
2
3
4
5
<script>
var require = {
// put config key-value pairs here
};
</script>

Of course, you can use these two method together as your will.

Application Logic with Utility Scripts

With the use of RequireJS, the web application has been devided into a series of small utilities. Because of this change, some other change need to be applied to project structure and application logic.

In your main.js, after setting up the requirejs.config(), you can tell RequireJS what utilities will be used in your application and how to use them, which is the main application logic. The specific structure goes like the following one:

1
2
3
4
5
6
7
8
9
10
11
12
requirejs([
// dependency list
"lib/jquery",
"lib/foo",
"util/bar"
],
// callback function
function($, foo, bar){
console.log("Application starts!");
// Your app logic goes here
});

It’s recommended to split large script into small pieces and load them via dependencise. This method may cause large amount of HTTP request which will significantly slow your app down. However, you can use optimizion tools to merge them together after development or before deployment. There are some tasks for Grunt or Glup from community to automatic this process.

Core entity: module

There is no doubt that the module is the core entity in RequireJS’s system. Here, let’s talk something about module. First, present an example here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* Module 1: object */
define({
"foo": "bar"
});
/* Module 2: function */
define(function() {
console.log("Hello Module");
});
/* Module 3: function with dependencies */
define([], function() {
// return anything legal is allowed here
return function() {
};
});
/* Module 4: CommonJS compitable layer */
define(function(require) {
// use CommonJS style here
var mod1 = require("mod1");
var mod2 = require("mod2");
return function() {
};
});

You can use any of the first three module in your module depends on what kinds of module you’re implementing. As for the lath one, it provides a compitable way to reuse exist CommonJS style module.

In official API document, there are also description on this topic you can refer to.

CC-BY-SA 4.0
The content of this post is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
END
Getting CAS Tickets via Node
Use Glup to Make Life Easy
Disqus is loading...