I would like to keep my JavaScript code modularized in different files, but would like to do so using native JavaScript objects like this:
(function ($, _, val) {
return {
myTest: 'abc',
init: function (options) {...}
};
})(jQuery, _, 'utils/validation');
Is there a script loader that can work like this? I've used RequireJS and don't want to wrap all my several files in define/require (although I really like the idea r.Optimizer). Any help or experience would be greatly appreciated!
If I understand what you are meaning, you want to load a separate JavaScript file after the page is loaded. I have an example that shows how you can have a module spread over multiple files and load additional pieces of that module at later calls. First, a great summary of different module patterns can be found here: Adequately Good: Module Patterns and a very nice code snippet that shows a JavaScript loader can be found here: Loading JS files Asynchronously
My Module's name is myModule
and it gets three functions during the initial load: addNumbers()
, doOperations()
, and difNumbers()
. Then after the document is loaded, we store in tmp
the answer to doOperations()
. After that, we want to load the multiply.js
script so that myModule
has the multNumbers()
function, so we call loadScript()
with the URL to the file, and give it a callback that will print the multiplication to the console.
Here is my code:
HTML File
<html>
<head>
<title>Module Pattern</title>
<meta charset="UTF-8">
<script>
var myModule = (function(my) {
my.addNumbers = function(a, b) {
return a + b;
};
return my;
}(myModule || {}));
</script>
<script>
var myModule = (function(my) {
my.doOperations = function(a, b) {
return{
c: my.addNumbers(a, b),
d: my.difNumbers(a, b)
};
};
return my;
}(myModule || {}));
</script>
<script>
var myModule = (function(my) {
my.difNumbers = function(a, b) {
return a - b;
};
return my;
}(myModule || {}));
</script>
<script>
function loadScript(url, success) {
var script = document.createElement("script");
script.src = url;
var head = document.getElementsByTagName("head")[0],
done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState ||
this.readyState === "loaded" ||
this.readyState === "complete")) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
</script>
<script>
function main() {
var tmp = myModule.doOperations(5, 6);
loadScript("multiply.js", function() {
console.log(myModule.multNumbers(7, 9));
});
console.log(tmp.c);
console.log(tmp.d);
}
</script>
</head>
<body onload="main();">
<div>I do operations</div>
</body>
</html>
multiply.js
var myModule = (function(my) {
my.multNumbers = function(a, b) {
return a * b;
};
return my;
}(myModule || {}));