The following example will demonstrate a basic installation and setup of RequireJS.
Create a new HTML file called index.html
and paste the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello RequireJS</title>
<script type="text/javascript" src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script>
</head>
<body>
<!-- place content here --->
<script>
requirejs(["scripts/say"], function(say) {
alert(say.hello());
});
</script>
</body>
Create a new JS file at scripts/say.js
and paste the following content:
define([], function(){
return {
hello: function(){
return "Hello World";
}
};
});
Your project structure should look like this:
- project
- index.html
- scripts
- say.js
Open the index.html
file in a browser and it will alert you with 'Hello World'.
Load the require.js script file.
<script type="text/javascript" src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script>
Load the say
module asynchronously from the scripts
folder. (Note that you do not need the .js
extension when referencing module.) The returned module is then passed to the provided function where hello()
is invoked.
<script>
requirejs(["scripts/say"], function(say) {
alert(say.hello());
});
</script>
The say
module returns a single object with one function hello
defined.
define([], function(){
return {
hello: function(){
return "Hello World";
}
};
});