Maybe I'm late to answer this question.
My current solution is to add <script> tags recursively so that adding the next script is in the callback of its predecessor. It assumes that each function contains one function, and this function matches the file name (minus the extension). This may not be the best way to do something, but it works fine.
Code to review
Directory directory structure:
- directory
index.html
<head> <script src="bundle.js"></script> </head>
bundle.js
// Give JS arrays the .empty() function prototype if (!Array.prototype.empty){ Array.prototype.empty = function(){ return this.length == 0; }; }; function bundle(module_object, list_of_files, directory="") { if (!list_of_files.empty()) { var current_file = list_of_files.pop() var [function_name, extension] = current_file.split(".") var new_script = document.createElement("script") document.head.appendChild(new_script) new_script.src = directory + current_file new_script.onload = function() { module_object[function_name] = eval(function_name) bundle(module_object, list_of_files, directory) /* nullify the function in the global namespace as - assumed - last reference to this function garbage collection will remove it. Thus modules assembled by this function - bundle(obj, files, dir) - must be called FIRST, else one risks overwritting a funciton in the global namespace and then deleting it */ eval(function_name + "= undefined") } } } var test_module = {} bundle(test_module, ["a.js", "b.js", "log_num.js", "many_parameters.js"], "test_module/")
a.js
function a() { console.log("a") }
b.js
function b() { console.log("b") }
log_num.js
// it works with parameters too function log_num(num) { console.log(num) }
many_parameters.js
function many_parameters(a, b, c) { var calc = a - b * c console.log(calc) }
SumNeuron May 09 '17 at 18:32 2017-05-09 18:32
source share