Skip to content

Instantly share code, notes, and snippets.

@shibukawa
Created April 13, 2016 03:41
Show Gist options
  • Save shibukawa/edb4c0895c2a5de64e9587d255015fc4 to your computer and use it in GitHub Desktop.
Save shibukawa/edb4c0895c2a5de64e9587d255015fc4 to your computer and use it in GitHub Desktop.
mithril lazy loading
var m = require("mithril");
m.mount(document.querySelector("#menu"), {
view: function() {
return m("ul", [
m("li", m('a[href="/a"]', {config: m.route}, "module A")),
m("li", m('a[href="/b"]', {config: m.route}, "module B")),
m("li", m('a[href="/c"]', {config: m.route}, "module C"))
]);
}
});
var loaded = {};
var lazyModuleA = {
view: function (ctrl) {
if (loaded.module_a) {
return loaded.module_a;
} else {
m.startComputation();
require(["./module_a.js"], function(module_a) {
loaded.module_a = module_a;
m.endComputation();
});
}
}
};
var lazyModuleB = {
view: function (ctrl) {
if (loaded.module_b) {
return loaded.module_b;
} else {
m.startComputation();
require(["./module_b.js"], function(module_b) {
loaded.module_b = module_b;
m.endComputation();
});
}
}
};
var lazyModuleC = {
view: function (ctrl) {
if (loaded.module_c) {
return loaded.module_c;
} else {
m.startComputation();
require(["./module_c.js"], function(module_c) {
loaded.module_c = module_c;
m.endComputation();
});
}
}
};
m.route(document.querySelector("#content"), "/a", {
"/a": lazyModuleA,
"/b": lazyModuleB,
"/c": lazyModuleC,
});
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<body>
<div id="menu"></div>
<div id="content"></div>
<script src="js/app.js"></script>
</body>
</html>
var m = require("mithril");
console.log("module A is loaded");
module.exports = {
view: function () {
return m("h1", "module A");
}
};
var m = require("mithril");
console.log("module B is loaded");
module.exports = {
view: function () {
return m("h1", "module B");
}
};
var m = require("mithril");
console.log("module C is loaded");
module.exports = {
view: function () {
return m("h1", "module C");
}
};
module.exports = {
entry: {
app: "./src/app.js"
},
output: {
path: "./js/",
publicPath: "/js/",
filename: "[name].js"
},
resolve: {
extensions: ["", ".src", ".css"]
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment