Thursday Tech Tip – RequireJS

14 Nov , 2013 Technology,Thursday Tech Tips

Thursday Tech Tip – RequireJS

Yesterday, one of my colleagues gave a tech talk on RequireJS, which is an upcoming JavaScript library/resource for helping you manage, well, all of your other JavaScript libraries. Much of today’s web development is dependent on the tight and well-timed integration of multiple JavaScript libraries, plug-ins, etc. One of the key issues with this approach is that the use of multiple libraries creates interdependencies that are often contingent on the well-timed loading of various resources and/or objects into the DOM. If a resource in the DOM is not loaded at just the right time or the value of that resource is not set or changes, than the resources you are hoping to leverage from say, handlebars.js, won’t load correctly and your web application could fail.

Most of these problems stem from the fact that browsers load web pages and all of their JavaScript resources asynchronously. So, a developer cannot be 100% sure in what order resources will be loaded or moreover the value of an object in the DOM they may be looking for at the time their script loads. One current workaround for this issue has been to leverage one of the JQuery’s functions below.

$.onReady();

or

$(document).ready();

This step allows you to load your scripts when all the others aspects of the page have been rendered. However, it to has limitations in that you still have to carefully sequence the events within the onReady function and hope that you do not encounter any name collisions. Moreover, you will probably need to include a listener function of some sort to maintain access to whatever you resources and functions you have called from within the onReady function. So, enter RequireJS, a smart and configurable JavaScript Extension and Module loader.

<script data-main="scripts/main" src="scripts/require.js"></script>

With Require.JS you treat your JavaScript libraries as modules that you define in the RequireJS file and then use just one script reference in the head section of your site and let RequireJS do the rest. You can define a module as simply a Key/Value pair from one of your JS files all the way up to the library itself as a module. Using a loader that manages all of your scripts in a modular fashion can boost site performance by helping to load code quickly while keeping it short and concise. Many popular JavaScript libraries are already supporting or building in support for RequireJS. It also possible that core JavaScript (ECMAScript) will incorporate modular style script loading into its main functionality. RequireJS is still a growing standard so be prepared for a bit of a learning curve.

, , , ,


Leave a Reply