A 5-Minute Fix for Client-Side Spaghetti Code

Wildebeest
2 min readFeb 13, 2017

We’re currently working on a WebGL game using the three.js library and within a few days had 704 lines of code in one file, with the game only about 5% complete.

The feeling of hitting CMD+F in Sublime and typing in function name guesses was already unbearable. Something had to change. There are a few solutions:

  • Contain all modules within IIFYs.
  • Use a fancy bundler.
  • Load in a bunch of files in script tags and pollute the global name space (I don’t recommend this).

Another quick and easy-to-implement solution is RequireJS. Since RequireJS only initializes the modules once, it allows you to pass around the same objects to different modules. For example, the scene object may need to be passed to an obstacle module so it can be added to the scene. But the scene object also needs to be passed to the renderer so the scene can be rendered. This ensures you are always working with the same scene.

Another benefit to this approach is it makes dependencies easy to manage. If you need to add the sound module to your obstacle module, but both the sound and obstacles must be added to your app.js— RequireJS will take care of it all for you.

// app.jsdefine( ["three", "sound", "obstacle"], 
function ( THREE, sound, obstacle) {
// do stuff with sound and obstacle
}
);

RequireJS also makes it super easy to shim a module. You can shim each module in just one line of code.

requirejs.config({
shim: {
"three": { exports: "THREE" }
}
});

You also don’t have to create a build process. If you don’t have a go-to workflow for modularizing client-side Javascript, the start up cost is about as low as they come.

The only “gotcha” I have encountered while using RequireJS with three.js is there are a few libraries out there that work in conjunction with three.js that require THREE being available in the global space. And as one of the features of RequireJS is no global scope leak, this can cause an issue. An easy solution is to create a module that attaches THREE to the window. You can find more info about that here.

For a template of how to set up RequireJS with your three.js app check out this link:
https://github.com/felixpalmer/amd-three.js

And if you have a favorite method of organizing your three.js or other client-side Javascript, let us know in a comment.

Wildebeest is a product studio in Los Angeles, CA. This article was written by Rachel Okimoto, Front-End Developer.

Icon made by Freepik from www.flaticon.com

--

--

Wildebeest

A product studio in LA that builds custom software for brands.