Ads News
by Farmer Dane
May 29, 2017
Tagging Single Page Applications with the Facebook Pixel

Single Page Applications, known as SPAs, are front-end web applications using HTML, JavaScript and CSS. You typically use them with a combination of AJAX and HTML5 features such as History State API to manage URLs and routes, user interface, state and communication to a server.

Page Reloads and SPAs

On typical websites such as standard e-commerce sites or brochure-style sites, when we visit a URL, the page is reloaded each visit. So when we add Facebook Pixel, we can rely on putting the standard Facebook Pixel code in the page header or footer with standard or customer events and the pixel fires on each page reload.

SPAs do not require a page to reload in browsers when the URL changes, so your Facebook Pixel cannot rely on the reload to trigger event firess. So you need a different approach to tag the application with the Facebook Pixel.

Strategy for tagging SPAs

This outlines general approaches you can use to tag your SPA site for the Facebook Pixel. In your application and framework you should use the HTML5 History State API to manage URL changes as a best practice. The general steps you should perform are:

  • Base Code Setup
  • Track PageViews
  • Track specific areas of your SPA

Base Code Setup

On initial Page Load, you should insert FB Pixel JS code into the page's header or footer. Alternately you can inject it with a Tag Manager. The only change you need to make to your code is to adjust how Facebook Pixel tracks PageViews with the History State API listener provided in the pixel.

Tracking PageViews

By default Facebook Pixel activates the HTML 5 History State API listener. This means that each time a new state appears in the history, such as history.pushState, Facebook Pixel fires a PageView event. Note that due to the way we designed Facebook Pixel's JavaScript code, you cannot fire more than one PageView event explicitly without this listener.

You should leave the listener on and let it track PageViews when you SPA's URL changes. This Facebook Pixel feature also manages the referrers and URLs so you can also use and track Custom URL conversions.

If you do not want this default behaviour, you can turn it off using the flag disablePushState. When you sest this flag to "true" it stops sending PageView events on history state change. For example:

<script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
document,'script','https://connect.facebook.net/en_US/fbevents.js');

fbq.disablePushState = true; //not recommended, but can be done

fbq('init', '<PIXEL_ID>');
fbq('track', 'PageView');
</script>

Tracking Specific Areas

You may have scenarios where you want to tag key areas in your SPA differently and beyond the simple PageView event. You may want to do this for measurement, optimization and reporting reasons. For example, you may want to track each step of a registration form or key behaviour such as a completed registration, submit lead form or purchase.

If you want to do this, you shoule use one of the nine Facebook Pixel Standard Events and tag the areas in your web applications.

The example below illustrates a jQuery &quot;application&quot; that mimics SPA behaviour. It does this by implementing JavaScript listeners and using History State API with and without a tag manager.

Based on the link someone clicks this happens:

  • link1.html: ViewContent Standard Event fires
  • link2.html: AddPaymentInfo Standard Event fires
  • link3.html: Purchase Standard Event fires

Tracking without Tag Managers

You cannot follow a single, standard solution since it depends on you framework and implementation. However, you should try to fire the event whenever a URL changes in your SPA. This requires you to connect the pixel logic to your framework's or application's routing logic. For an example, see this commented HTML File: spa_no_gtm.html

In the following example:

  • A routing change is simulated when a link on the page is clicked, on lines 23-31
  • The &quot;grabContent&quot; function simulates a call to the server where new content is grabbed and a history.pushState function is called to change the URL of the SPA
  • The tracking event with the different events is called on line 83: fbq('track' …. );

Tracking with Tag Managers

Using a Tag Manager to tag a site enables you to have a maintainable, scalable solution to manage all tags. With it, you can have many tagged items and anyone can be change them in a user-friendly interface as opposed to requiring developers to make changes each time.

The following example uses Google Tag Manager, or GTM, as one way to demonstrate this.

In the following example:

  • A routing change is simulated when a link on the page is clicked, on lines 30-36
  • PageView event is fired by the FB JS Pixel code on each URL change. This is the default behaviour
  • The Standard Events are set and triggered from within GTM

Get the example HTML File, with comments: spa_gtm.html

Setting Up GTM requires:

  • Putting the GTM code on the webpage
  • Creating each tag within GTM
  • Creating a Listener for the History State API changes
  • Creating a trigger for each particular page to fire the FB Pixel event

Creating Tags in GTM:

The tag is the snippet of code to fire Standard Events. This shows a CompleteRegistration event being set up to fire. In more complex examples, you can also incorporate dynamic variables from your data layer.

Creating a Listener for State Changes: For a general listener, you need to set up History Change so GTM listens and fires a gtm.historyChange event when it detects a push state change, or any URL change in your application.

Note that GTM also fires the push event when someone selects your back option. So if someone can move ahead and backwards your application's flow, be aware that events can fire multiple times.

Creating a Trigger to fire the Tag: You need to set a Custom Event trigger along with the history state listener you set up earlier. This can then fire the tag.

Final View of Triggers

To debug, you can use the dataLayer plugins and the Network Tab in Chrome Developer tools to see if the events are firing as needed.

Brief Background on SPAs

Single-Page Applications are Web apps that load a single HTML page and dynamically update that page as the user interacts with the app. SPAs use AJAX and HTML5 to create fluid and responsive Web apps, without constant page reloads. Source: Single-Page Applications: Build Modern, Responsive Web Apps with ASP.NET.

This describes a fundamental difference in the way that SPAs and traditional web application requests happen where SPA applications do not initiate a page refresh or reload.

SPAs are becoming more prevalent these days for several business and technical reasons. You can them use them based on on technical resources available, application infrastructure, and considerations around maintainability and performance. You can write a SPA for a web application interface given certain situations.

To create a SPA, you can use several popular JavaScript frameworks which provide reusable building blocks. This includes views, routing systems, design patterns to separate responsibilities and so on. The enables you to efficiently create several types of applications. Some popular frameworks include:

  • Angular.js
  • Backbone.js
  • Ember.js
  • Knockout.js
  • Meteor.js
  • React.js
  • Vue.js

You don't have to use one of these frameworks, since your ability apply the patterns around SPAs is based on yor knowledge and skills using AJAX and HTML 5 features. So for example, you could natively implement one simple JavaScript application, or create an application with jQuery and related plugins.