After playing around with AMD/RequireJS I was wondering if it is a good idea to load UI modules including templates and CSS so they are completely independent from the web page.
It sounds like good, but I haven't seen this implemented in the wild so there may be pitfalls.
Think of some UI module with the following structure:
myWidget |--img |--main.js |--styles.css +--template.tpl
All stuff in one folder. Looks very nice.
The module in main.js would look something like this:
define(["TemplateEngine", "text!myWidget/template.tpl"], function(TemplateEngine, template) { // Load CSS (Pseudo Code) var cssUrl = "myWidget/styles.css"; appendToHead(cssUrl); return function() { return { render: function(data) { return TemplateEngine.toHtml(template, data); } } } });
Questions are now:
To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.
RequireJS loads each dependency as a script tag, using head. appendChild(). RequireJS waits for all dependencies to load, figures out the right order in which to call the functions that define the modules, then calls the module definition functions once the dependencies for those functions have been called.
Generally you only use RequireJS in its loading form during development. Once the site is done and ready for deployment, you minify the code. The advantage here is RequireJS knows exactly what your dependencies are, and thus can easily minify the code in the correct order.
2 Answers. Show activity on this post. require(["jquery"], function ($) { function doStuff(a, b) { //does some stuff } $('#the-button'). click(function() { doStuff(4, 2); }); });
You can specify the template as a dependency using the text! module like you have shown. I do this with Mustache Templates.
However Require.js does not explicitly support css files.
Here is the official explanation, it's explained pretty well: http://requirejs.org/docs/faq-advanced.html#css
Edit: Feb 2012.
Templates such as handlebars can also be precompiled and included just like any other JS module http://handlebarsjs.com/precompilation.html
Edit: August 2015
If you're after this sort of modularization you should look into webpack and specifically css-loader. I'm using it to pair .css files with .jsx files as a unified "module" and extract the relevant CSS into a single stylesheet at build time.
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