← back to the blog


Creating AMD Compatible JavaScript Files

Posted in JavaScript

Lately I've been using the Require.js library a lot to modularize my front end JavaScript applications. Require.js expects 'AMD compatible' JavaScript files that have the main program wrapped inside a define([], function(vars) {}) function. This format allows the file to explicity call out any files it depends on so that a library like Require.js can load all the files in the right order. The advantages are three fold:

  1. Race conditions are avoided by loading scripts in an explicit order.

  2. JavaScript files can be called on an as-needed basis rather than front loading everything, thus improving performance.

  3. It allows complex JavaScript programs to be modularized into small files that are mission specific. This is a best practice that helps with maintenance and collaboration.

The problem with wrapping a JavaScript file in this kind of function is that it breaks it's ability to work with normal HTML files that call JavaScript files with a <script> tag. The reason is that the global define() function doesn't exist unless your using an AMD loader like Require.js. This becomes a serious issue when trying to use a common file to store settings, like server IP addresses, ports, admin email addresses, etc. Attempting to share this file between your AMD app and normal HTML files isn't possible.

Through a lot of trial an error, I was able to create the following serverData.js file for use in my latest program:

/*
 * This file is the central location for setting the server info. It is set up to work with both vanilla JS files as well as AMD/Require.js enabled JS files.
 */
function getServerData() {
  
  var serverData = {

    //Development Server
    serverIp: '192.241.198.211',
    serverPort: '80', //Not Used
    mailPort: '8888',
    adminEmail: 'chris.troutner@gmail.com',

    //Separate each email address with a comma
    additionalEmails: ''

    /*
    //Production Server
    serverIp: '198.199.101.123',
    serverPort: '80', //Not Used
    adminEmail: 'ctroutner@skagitpublishing.com',
    additionalEmails: 'test@test.com,admin@test.com,marketing@test.com'
*/ } return serverData; }; //This little bit of code handles AMD enabled JS files that expect a define() function. if ( typeof define === "function" && define.amd ) { define([], getServerData ); }

 

That last little code paragraph takes care of the AMD program. If the HTML file doesn't use AMD, it simply skips it. The function on top is 100% compatible with a normal HTML/JavaScript scheme. When this file is attached to an HTML file with a <script> tag, the getserverData() function becomes a global object. It can simply be called and the return value dumped into a local variable in order to get the server information. 

Voila! All the important server information, emails, etc in one single location. This makes updates and maintenance easy.