Skip to content

Instantly share code, notes, and snippets.

@nessthehero
Created October 28, 2014 17:46
Show Gist options
  • Save nessthehero/aa0899d2787a97d5f450 to your computer and use it in GitHub Desktop.
Save nessthehero/aa0899d2787a97d5f450 to your computer and use it in GitHub Desktop.
Modular Example (Gist Form)

Modular JavaScript

This is a basic example of writing modular JavaScript.

In the example file, we are only loading one script, and loading modules based on feature detection.

The "a" span was detected by jquery, so that module is loaded.

There was no tag with "b", so that module was not loaded.

Entire modules and/or libraries could be loaded based on feature detection, or other criteria (routing, media queries, etc)

define(function () {
return {
status: function () {
console.log("Hello from A!");
}
}
})
define(function () {
return {
status: function () {
console.log("Hello from B!");
}
}
})
<!DOCTYPE html>
<html>
<head>
<title>My Sample Project</title>
<!-- data-main attribute tells require.js to load
scripts/main.js after require.js loads. -->
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<h1>My Sample Project</h1>
<span class="a"></span>
</body>
</html>
require.config({
baseUrl: 'scripts/helper',
paths: {
jquery: 'jquery'
}
});
require(["jquery"], function(jquery) {
if (jquery('.a').length !== 0) {
require(["a"], function (a) {
a.status();
});
}
if (jquery('.b').length !== 0) {
require(["b"], function (b) {
b.status();
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment