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.

Sponsored Post Learn from the experts: Create a successful blog with our brand new courseThe Blog

Are you new to blogging, and do you want step-by-step guidance on how to publish and grow your blog? Learn more about our new Blogging for Beginners course and get 50% off through December 10th. is excited to announce our newest offering: a course just for beginning bloggers where you’ll learn everything you need to know about blogging from the most trusted experts in the industry. We have helped millions of blogs get up and running, we know what works, and we want you to to know everything we know. This course provides all the fundamental skills and inspiration you need to get your blog started, an interactive community forum, and content updated annually.