Reputation: 97
What is the use of a module loader? How it can be use in JQuery? How to use require.js as module loader. Please share the sample application too. if you have!!
Upvotes: 1
Views: 3993
Reputation: 631
Ok I go in parts
What is a module loader?
OK In Js you can't use a import instruction (well yes in node you can.) so many people stick their code all together (even the librarys their using) so they don't have to load anything, but this can bring large js files and add load time to your app, other people think that they separate the code and use the tag to load by pieces but this is unpractical as you have to maintain all definitions in the html pages, so here is were require.js comes and help you to decopule your code by creating modules and load then on demand. this make easy to separate your code and have small pieces easier to fix, maintain or add features.
from require.js docs
"When a project reaches a certain size, managing the script modules for a project starts to get tricky. You need to be sure to sequence the scripts in the right order, and you need to start seriously thinking about combining scripts together into a bundle for deployment, so that only one or a very small number of requests are made to load the scripts."
How it can be use in JQuery?
I will change the question to How it can be use with JQuery?
You will load Jquery as an dependency when is need it you have a basic example here
How to use require.js as module loader?
here a little snippet of code
the html need it
<!DOCTYPE html>
<html>
<head>
<title>jQuery+RequireJS Sample Page</title>
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
</head>
<body>
<h1>jQuery+RequireJS Sample Page</h1>
</body>
</html>
Our main.js
require(["jquery", "jquery.alpha", "jquery.beta"], function($) {
//the jquery.alpha.js and jquery.beta.js plugins have been loaded.
$(function() {
$('body').alpha().beta();
});
});
part of the config
paths: {
"jquery": "require-jquery"
},
modules: [
{
name: "main",
exclude: ["jquery"]
}
I hope this can help you. You can download an example project here
I will add an example of my app so you can see how use Backbone and require
the config
require.config({
shim: {
'underscore': {
deps: ['jquery'], //dependencies
exports: '_' //the exported symbol
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
paths: {
jquery: 'libs/jquery/jquery-1.7.1.min',
underscore: 'libs/underscore/underscore-min',
backbone: 'libs/backbone/backbone-min',
}
});
An example module
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
//Your code Here
});
Have fun working with require :-)
Upvotes: 9