Loading Google Maps with RequireJS

Recently at REA, we’ve started to use RequireJS on a few projects to help modularize our Javascript. I came across a fairly subtle issue when trying to use the Google Maps JS API with RequireJS which I thought was interesting.

Here’s our situation:

  1. We want to load google maps and let our code treat it as an AMD module.
  2. We have several third-party libraries that depend on Google Maps and aren’t AMD modules; we of course want to treat them as AMD modules so we’ve shimmed them.
  3. We want to use r.js to build a single JS file for production.

Because Google Maps loads asynchronously, we can’t simply shim it. Miller Medeiros’ async plugin seems to be a common (and good) solution to this problem. His blog post describes the technique, but it doesn’t mention a couple of potential gotchas to do with shimmed modules and single-file optimized builds.

With the async plugin, Google Maps is a “real” AMD module from RequireJS’ perspective. As explained in the RequireJS docs, shimmed modules can’t depend on real modules, because RequireJS has no way ensure in the built file that the shimmed module executes after the real modules it depends on.

This implies that in the built version of the code, we’ll need to load the Google Maps API separately, before all our RequireJS modules (what the RequireJS docs refer to as “CDN loading”). But we’ll also need a way to load Google Maps via the async plugin, only in the non-built environment (otherwise we’d get two copies of Google Maps after the build).

So our complete solution consists of a gmaps.js containing:

define(['async!http://maps.google.com/maps/api/js?v=3&sensor=false&client=gme-nsp&channel=new-homes-app'], function () {
return google.maps;
});

as in the blog post, but for the built version of the code, we created a gmaps-stub.js containing:

define(function () {
    return google.maps;
});

and in our build config, loaded the stub instead:

paths: {
    gmaps: 'gmaps-stub'
}

This lets us meet all three of the above requirements.