Issue
I have problem with requirejs, and importing modules on conditions. For example I have login page, with some modules. Some off them use only when user is logged, another when user is not logged. Of course I don't want users ability to register, when they logged in. So I have two difrent solutions:
First solution: require only things I needed:
define(['jquery', 'dst!/static/dust/frontend/user_menu.dust'], function($, template) {
var handleResponse = function(data) {
if (data.status == 'not_logged') {
require(["user/frontend/register"]);
require(["user/frontend/login"], function(l) {
});
} else {
require(["user/frontend/logout"]);
require(["user/frontend/change_password"]);
require(["user/frontend/profile_details"]);
}
template(data, function(err, html) {
$('#userMenu').html(html);
});
};
$.ajax({
url: '/user/info/',
type: 'GET',
success: handleResponse
});
});
That give me extra easy to read code, but I can't optimizes it with r.js tool.
Second solution:
define(['jquery', 'dst!/static/dust/frontend/user_menu.dust',
'user/frontend/register', 'user/frontend/login', 'user/frontend/logout',
'user/frontend/change_password',
'user/frontend/profile_details'], function($, template, register, login, change_password, profile_details) {
var handleResponse = function(data) {
if (data.status == 'not_logged') {
register.init();
login.init();
} else {
logout.init();
profile_details.init();
change_password.init();
}
template(data, function(err, html) {
$('#userMenu').html(html);
});
};
$.ajax({
url: '/user/info/',
type: 'GET',
success: handleResponse
});
});
It's hard to read. Everything is loaded to memory.
Maybe there are some another options to do it?
Solution
Check out a little library I created: require-lazy
It allows you to lazy-load modules with an easy syntax:
define(["lazy!moduleWhenLogged", "lazy!moduleWhenAnonymous",
function(moduleWhenLogged, moduleWhenAnonymous) {
...
if( logginSucceeded ) {
moduleWhenLogged.get().then(function(realModule) {
...
});
...
});
Lazy loaded text too!
define(["lazy!text!foo.html", ...
And works with r.js (i.e. bundles different modules into separate JS files, according to the dependency graph).
Not a lot of documentation yet, but I have lots of examples. There are also Grunt, Bower plugins.
Answered By - Nikos Paraskevopoulos
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.