I am new to requireJS and tring to learn it so that i can use it in my current application.
While reading API documentation of requireJS, I came across bundles (http://requirejs.org/docs/api.html#config-bundles) as configuration option of requireJS
requirejs.config({
bundles: {
'primary': ['main', 'util', 'text', 'text!template.html'],
'secondary': ['text!secondary.html']
}
});
require(['util', 'text'], function(util, text) {
//The script for module ID 'primary' was loaded,
//and that script included the define()'d
//modules for 'util' and 'text'
});
API Explanation :
Bundles config is useful if doing a build and that build target was not an existing module ID, or if you have loader plugin resources in built JS files that should not be loaded by the loader plugin.
But here I am not able to understand that why we need bundle and when we should use use it?
RequireJS is, in web-terms, an old technology now (some might say ancient), but it is still in wide use and there have been a number of questions about RequireJS and DataTables recently.
RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.
JavaScript bundling is an optimization technique you can use to reduce the number of server requests for JavaScript files. Bundling accomplishes this by merging multiple JavaScript files together into one file to reduce the number of page requests.
a javascript module loaderRequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
When building a large SPA (Single Page App), it is imperative that you concatenate and minify your files. The problem with doing it, is that you might end up with one massive minified js file that can get as large as a few megs.
In order to solve this, require introduces the bundle feature, which allows you to pack your files in several bundles, and those would be loaded only when needed.
So, for example if you have a page with 'home' and 'about', you can create a bundle like:
bundles: {
'home': ['home', 'util', 'text', 'text!home.html'],
'about': ['text!about.html']
}
and then the about page resources would only be served when you actually click the about page. That way you get lazy loading of resources.
For better explanation and example, watch this great video: http://vimeo.com/97519516
The relevant part is around the 39 min.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With