How to bring modularity & dependency management to Javascript
JavaScript is a super dynamic language, a little too much at times. Firstly it has no linker and a single global namespace, this means nothing is private (without a bit of effort) and absolutely everything needed for a Javascript application must be manually included in the pages’ source. Secondly its fluidity allows for bad design, we’ve all been there; it’s 5am, PLEASE I JUST WANT TO SLEEP, so a little mini hack creeps in…that’s ok if it’s just the one. Over time the code becomes a mangled mess.
What we could all do with is something that knows what particular piece of code is needed, goes and gets it and then makes it available for use. Such a piece of kit would solve lots of headaches and have the fringe benefit of allowing code to be small and modular (i.e. without having to manually include millions of tiny scripts). Struggle no more because such a thing exists!
There are many JavaScript solutions to the problem ranging in complexity and compatibility, we settled on requireJS but they all follow the same basic pattern: the ability to define a ‘thing’ and the ability to say I need a ‘thing’. In requireJS this is achieved by two global functions ‘require’ and ‘define’. The library takes care of all the difficult things like load order and how best to dynamically include scripts in the page (that means you IE). An added bonus with requireJS is that three very helpful plug-ins are available – one for pulling in CSS, one for pulling in text and another for handling locale specific messages.
So what’s this done for us? It’s made all our lives easier and allowed us to get down to what we do best – that’s not tracking down a missing JS file, that’s not finding where that one global function is defined, it’s getting on with building super cool awesome stuff.
Writer Alex Bell, Senior Software Engineer at Dotted Eyes, 19th September 2013