Sunday, 20 January 2013

Some thoughts about RequireJS


Being keen to learn about the new JavaScript libs I was wondering how useful RequireJS is. The library is defined by the following:


RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

The way it works is that you create an entry point of all scripts. There you can define your local file structure, some scripts, versions and other preferences. The next thing is to load the actual files - or modules the site is relying on. In the loaded structure you can keep your business logic separate and all parts will know the requirements. Of course all of that will be loaded asynchronously.

At this point I've ended up at a very interesting structural organization of JavaScript: modules. This article explains how you can organize your code for reusability and extensibility. That's a key part in using RequireJS. I was wondering a lot what would be the smart way to distribute the typical JS layout - hundreds of more or less independent functions. Well, first you centralize them around entities (or class like things, whatever). The using the aforementioned module patter you can easily define the separate extensible parts in several files. Now RequireJS can make it easy for you to load them only the necessary bits.

Following that line a little it helps on scoping and code clean. Well, just like an angry raptor on the kindergarden. RequireJS - when loading a dependency - scope them to the argument list. It makes sure you access them in that scope, and only to that one module. Preferably no globals, no namespace collision anywhere. At this point I have to note - I'm not that happy formatting my code to a particular library. There I said it. However if you're willing to stick with it then it's a great thing.

An extra of the library is that it supports loading JSONP resources as well over the network. It has a nice jQuery integration and some handy NodeJS tool for building apps.

---

Being so far less competent in RequireJS than stuffed leather goose I rather create some debate how and when to use RequireJS. My 2 cents is that is great when you dedicate yourself to the convenient structure it expects. It's great when you have a high variation of possible JS loads on the page. And last but not least when it's uncertain when you want to access to something - if it's required at all to load.

Have you ever used RequireJS in a large (or Drupal) project? What do you think?

Peter

No comments:

Post a Comment