Making javascript files include each other

Developing web-applications, I’ve never liked having to declare all the scripts I want the webpage to load in the HTML. In almost any other programming language I use, I declare the dependency of a file in that file: “include” for C++, “import” for Java, “require” for lua, etc.

For my WebGL project I’ve been usingĀ requirejs, but for some reason it kept failing to load my scripts prior to the execution of my “main function” code. Also, I was declaring all the files I wanted requirejs to load in one place. I want a javascript file to state its own dependencies, rather than have a single script declare the dependencies for all the scripts. So I decided to investigate a little how hard it would be to emulate javascript dependencies in the webpage.

Turns out it was actually incredibly easy to do.

I declare a function called “include” which takes a script name (with relative path) and run a small piece of code that looks up a “entry script” that I declare in my index.html. I’ve named the script “include.js”.


This element loads the “include.js” script and tells it that the “scripts/main” script will be the “entry script”. Then I can go ahead and invoke “include” in my scripts every time one script needs the other. Once “include.js” has loaded all the scripts that were supposed to be, well, “included”; it looks for and invokes a “main” function. The script paths are relative, so I don’t have to worry about having to change my code in scripts where folders “higher up” are renamed. All in all, it’s working just as I hoped.


I put a copy of include.js here. But I’ll probably keep it maintainedĀ here.