Some tricks to make JavaScript projects manageable

Most of the code in used to sit in one file – player.js. As I added the code for essential capabilities, the file began to grow. It finally got to the point where I often spent more time navigating the file than actually adding code. At the very least, I needed to break it up into multiple files.

But, what would be the best way to break things up into files? And how would I “include” those files into my project when JavaScript doesn’t have includes? Finally, how would communication work? Making calls across files means opening up multiple files later to track bugs across files!

Problem 1: How to include multiple files in a JavaScript project.
Solution: Use JavaScript to create a Script elements for each external file and add them to the document. Here’s how I did it for

Problem 2: Logical structure for dividing the files?
Solution: Divide the project up into modules. I read Anthony Colangelo’s“The Design of Code: Organizing JavaScript”, which is a great write-up on creating modules in JavaScript.

Problem 3: How will the modules communicate?
Of course, one can use ModuleName.methodName() to make method calls.
But there is a better way for certain situations: We can create JavaScript Events that each module can independently trigger and/or respond to!
I read How to Create Custom Events in JavaScript by Craig Buckler. Each module responds to a custom event called playrStatusChanged and then acts accordingly.