HomeAbout UsNews, company reports and blogBlogTechLoading Google Maps with RequireJS

Loading Google Maps with RequireJS

Article by Eric Entzel
Published on Read in 2 mins

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.

More from the blog

My first rotation as a Springboarder at REA.

Category: Career stories
Published on

From Teaching to Software Development – A Year On

Category: Career stories
Published on

A vision of the future is a bet we are prepared to make

Category: Tech
Published on

One year at REA: Lessons, Growth, and Gratitude

Category: Life at REA
Published on

Introducing Argonaut – Part Three.

Category: Tech
Published on

Introducing Argonaut – Part Two.

Category: Tech
Published on

View all articles