Google Publisher Tags and React Playing in Harmony

Doing Google Publisher Tags the React Way

For all the wonders Webpack and Babel have brought to Front-End JavaScript, the modern, modular applications you build with those tools don’t play well with third-party, drop-this-JavaScript-snippet-in-the-head-tag libraries.

For example, Google Publisher Tag (aka GPT) has a great API and lots of clear documentation. Unfortunately, they expect something clunky and external to your nice, modern bundled ES2017 application. They expect something like this at the top of your markup:

Meanwhile, the rest of your modern, modular, ES2017 application code looks like a jumble of () => {} Arrow Functions, class keywords, const and let and import and ... and… you get the idea.

By comparison, GPT’s closure-y architecture feels retro.

Reconciling Retro Libraries with Modern Application Code

Alright, so very recently, I was working on a project in which I needed to fix a race condition between GPT and a React component. What would happen was that React would render the DOM (including all the ad containers), fire all their respective component-lifecycle events before GPT was ready.

After treading water and pulling my hair out for hours, I stumbled upon a very simple way to keep everything in sync.

First, you need do load GPT in your head tag. Duh:

var googletag = googletag ||{};
googletag.cmd = googletag.cmd ||[];

Now you can let the <script async="async" src="https://www.googletagservices.com/tag/js/gpt.js"> take its sweet time loading, because you have that handy-dandy cmdArray.