Origami Frontend Components & Services

Readme: o-ads

o-ads is not maintained by the Origami team. This means that the Origami team will not necessarily be able to help you with support requests. The people who maintain this component may be able to offer support, but it's not guaranteed.

This package contains the core functionality used by the FT in providing ads across all of its sites. This includes ft.com, howtospendit.com, ftadviser.com and other specialist titles.

This doc is specific to the o-ads library. For more information about the ads ecosystem at the FT, visit the Ads wiki

Note: This package is over 5 years old and will soon be deprecated in favour of more modern tools. Please speak to the advertising team (Slack #advertising-dev) if you are thinking of using this.

Table of Contents

1. Install

2. Setup & Configuration

3. Define Ad Slots

4. Targeting

5. Lazy Loading

6. Invalid Traffic

7. Styling

8. Events

9. Metrics & Monitoring

10. Misc

11. Developing

12. Migration

Install

Step One. You need to include the o-ads library on your site. There are two ways:

1. Include a script on your site

The simple way. All you need to do is include the following in the <head> section of your site.

<href="https://www.ft.com/__origami/service/build/v2/bundles/css?modules=o-ads@^16.0.0" />
<script src="https://www.ft.com/__origami/service/build/v2/bundles/js?modules=o-ads@^16.0.0" async />

Note: At the time of writing, latest version of o-ads is v16.0.0. Check latest available version and replace in the script and link tags

2. Include o-ads as part of your build

If you're using a build system, you can include o-ads in your code through npm

npm install @financial-times/o-ads --save

And in your file

import oAds from '@financial-times/o-ads'

Setup & Configuration

Intialise the library

Step two. You'll need to initialise the o-ads library with some confirguration options in order for it to work. There are 2 ways of doing this:

Declaratively

If you've included o-ads directly on your site using the script provided above, you'll need to initialise it declaratively like so:

<script data-o-ads-config type="application/json">
{
  "gpt": {
    "network": 5887,
    "site": "test.5887.origami"
   }
}
</script>

Note: See below for all config options

### Programatically

If you've include o-ads in you code through npm, you will need to initialise it like so:

// your/app/ads.js
import oAds from '@financial-times/o-ads';
oAds.init({
  gpt: {
    network: 5887,
    site: "test.5887.origami"
  }
  ...other config options
});

Note: See below for all config options

Configuration Options {#config-options}

These are all the valid configuration options that can be used to set up o-ads:

Define Ad Slots

Step three. Create some ad slots. Once you've included and configured o-ads onto your website, you'll want to create some placeholders for your ads. These are the HTML elements where the ad will render. These can be defined declarately within a HTML page.

The Simplest Ad

This is the minimum required for an ad slot to be defined. We set some options via html attributes on the slot element. We are naming the ad slot exampleAdSlot and tell it to only return ads of the format MediumRectangle. This will be processed by o-ads and an ad will be rendered inside the <div> if the ad request is successful.

<div 
  data-o-ads-name="exampleAdSlot" 
  data-o-ads-formats-default="MediumRectangle" 
  aria-hidden="true">
</div>

See Ad Formats and Breakpoints

Ad slot options {#ad-slot-options}

These are all the options that an ad slot can have, declared as attributes on the html element (see example above)

Ad Formats

Formats are predetermiend ad sizes that you can request for your ad. You can specify one format as in the above example, or you can specify multiple formats for different breakpoints. The following example loads a MediumRectangle ad at the small breakpoint, a Leaderboard ad at the medium breakpoint a SuperLeader ad at the large breakpoint and no ad at the extra large breakpoint.

<div
  class="o-ads"
  data-o-ads-name="example"
  data-o-ads-formats-small="MediumRectangle"
  data-o-ads-formats-medium="Leaderboard"
  data-o-ads-formats-large="SuperLeaderboard"
  data-o-ads-formats-extra="false"
  aria-hidden="true">
</div>

Default breakpoints {#breakpoints}

The default breakpoints provided in o-ads are as follows:

Note: You can change the breakpoint definitions with the responsive config property:

oAds.init({
  ...
  responsive : {
    extra : [1400, 0],
    someOther: [1200, 0],
    large : [1000, 0],
    medium : [600, 0],
    small : [0, 0]
  }
  // where each array is in the format [width, height]
  ...
});

Default Formats {#formats}

Here are all the available ad formats and their corresponding ad sizes:

Format Name Size
MediumRectangle (MPU) 300x250
Rectangle 180x50
Leaderboard 728x90
SuperLeaderboard 970x90
Billboard 970x250
Responsive 2x2
WideSkyscraper 160x600
HalfPage 300x600
Portrait 300x1050
AdhesionBanner 320x50
MicroBar 88x31
Button2 120x60

Note: You can ad extra formats with the formats config option when initialising o-ads:

oAds.init({
  formats: {
    testFormat: {sizes: [[970, 90], [970, 66], [180, 50]]}
  }
});

Targeting

Ads can contain extra information about a user, page, or any other useful info that could be used in Google Ad Manager. There are three ways of adding targeting information to an ad request.

Page level targeting

You can specify an object of key => value pairs when initialising o-ads. Each key => value pair will be appended to every ad request on the page

oAds.init({
  ...
  targeting: {
    key: "value",
    key2: "value2",
    ...
  },
  ...
});

Ad slot level targeting

You can also specify targeting parameters for any particular ad slot, by using the data-o-ads-targeting attribute when defining the ad slot:

<div
  class="o-ads"
  data-o-ads-name="example"
  data-o-ads-targeting="pos=top;version=1;test=yes"
  data-o-ads-formats-default="MediumRectangle"
  aria-hidden="true">
</div>

Lazy Loading

o-ads can be configured to lazy-load ads (i.e. only trigger the ad call when the ad is in view, or close to being in view). It is disabled by default

Lazy Loading uses Intersection Observer under the hood.

oAds.config({
  lazyLoad: true
});

// or

oAds.config({
  lazyLoad: {
    viewportMargin: '0% 0% 100% 0%',
    threshold: [0.5]
  }
});

There is one exception to lazy loading, which is Master/Companion. Based on the way that this pair of creatives are related in DFP, the companion is loaded soon after the master, which overrides lazy loading.

Styling

o-ads provides some classes to add some basic branded styling to the ad slot.

Events

oAds.initialising

Triggered when the library starts the initialisation process.

oAds.initialised

Triggered when the library has been initialised and the config has been set. (Note: the GPT library may not have been loaded by this point).

oAds.serverScriptLoaded

Triggered when both the GPT library is loaded and oAds.initialised has happened. This marks the completion of the page-level tasks required to enable requests to the ad server.

oAds.adServerLoadError

Triggered if the library fails to load the external JS GPT library, meaning no advertising will work. Can be used if you wish to have a fallback when you know the adverts will not display.

oAds.slotReady

Slot has been inited in the oAds library and is about to be requested from the ad server (deferred if lazy loading is on).

oAds.slotRenderStart

Triggered once the ad has been rendered on the page.

oAds.slotExpand

If and when a creative has been returned, this event announces it has now been initialised in oAds, requested from the ad server and displayed. Triggered after oAds.slotRenderStart.

oAds.slotCanRender

Lazy loaded advert has been requested.

oAds.refresh

A refresh event has been triggered on an advert, prompting a new request to the ad server.

oAds.breakpoint

If the oAds is configured to use responsive adverts with set breakpoints, it will trigger the event on each of the breakpoints that was specified in the config. Note that the breakpoint triggering does not take the scrollbar into consideration. For more information read about DFP - Build responsive ads.

oAds.collapse

Event is emitted when the slot is collapsed. The event detail contains oAds slot instance.

Metrics & Monitoring

As of version 12, o-ads includes some built-in functionality to help monitor the ads loading flow.

Firstly, o-ads saves a performance mark every time it dispatches one of the many events that indicate a milestone in the ads loading process. If used from n-ads, extra performance marks might be added. See the n-ads docs

oAds.utils.setupMetrics()

o-ads is now exposing a new method, oAds.utils.setupMetrics() which enables setting up all ads-related metrics in one step.

```javascript
setupMetrics(eventDefArray, callback, disableSampling):

- `eventDefArray` **(required)** `<Array>`- An array of configuration objects, each of which corresponds to one group of o-ads events. Each config object must have these fields:
  - `spoorAction` **(required)** `<String>` - A string indicating the name of the group.
  - `marks` **(required)** `<Array>` - An array of strings indicating the name of the o-ads [events](#events) whose metrics we want to include in the group. Notice that the oAds. preffix must be omitted.
  - `triggers` **(required)** `<Array>` - An array of strings including all the o-ads events that cause the callback to be invoked.
  - `multiple` (optional) `<Boolean>` - Can the callback be called multiple times for the group? *Default:* `false`
  - `sampleSize` (optional) `<Number>` - Number between 0 and 1 indicating the probability the callback is actually called. If it’s omitted, the callback will be called every time one of the triggering events is dispatched.
- `callback` **(required)** `<Function>` - A function that will be invoked for each of those groups, possibly multiple times for each. When invoked, the callback will receive an object with information about the timings associated to the events in the group.
- `disableSampling` (optional) `<Boolean>` - A boolean indicating if the sampling specified in the `eventDefArray` should be ignored. That is, when set to true, no sampling will be applied. Default: `false`


### `setupMetrics()` Example
It’s easier to understand how to configure o-ads with an example:

javascript
const metricsDefinitions = [

{
    spoorAction: 'page-initialised',
    triggers: ['serverScriptLoaded'],
    marks: [
        'initialising',
        'IVTComplete',
        'adsAPIComplete',
        'initialised',
        'serverScriptLoaded',
  'consentBehavioral',
  'consentProgrammatic',
    ]
},
{
    spoorAction: 'slot-requested',
    triggers: ['slotGoRender'],
    marks: [
        'slotReady',
        'slotCanRender',
        'slotGoRender',
    ],
    multiple: true
},
{
sampleSize: 0.1,
    spoorAction: 'slot-rendered',
    triggers: ['slotRenderEnded'],
    marks: [
        'slotRenderStart',
        'slotExpand',
        'slotRenderEnded',
    ],
    multiple: true
}

];

function callback(eventPayload) {
nUIFoundations.broadcast('oTracking.event', eventPayload);
}

oAds.utils.setupMetrics(metricsDefinitions, sendMetrics);
}

In this example there are four different metrics groups. The first one will invoke the callback whenever the trigger (`oAds.serverScripLoaded`) is dispatched. The callback will receive an object including any available information about several potential time marks (`initialising`, `IVTComplete`, `adsAPIComplete`, `initialised`, `serverScriptLoaded`, …). If there is no information about any of those marks, the callback will still be called without it. Since the `multiple` parameter is missing, its default value of `false` is assumed which means that, once called, the callback will not be called again for the same page view even if, somehow, `oAds.serverScriptLoaded` was dispatched again.

`slot-rendered` and `slot-requested` config is similar to `page-initialised`. However, the `multiple: true` parameter allows the callback to be called as many times as their respective triggering events are dispatched during the same page view. Which, in this case, is the right thing to do since we expect a page to contain, potentially, multiple ad slots.

Finally, the `sampleSize: 0.1` parameter on the `slot-rendered` group randomizes the possibility that the callback is actually called when the `oAds.slotRenderEnded` event is dispatched, giving it only a 10% chance. This can be used to reduce the number of total “monitoring” events that get fired across the user base.

## `oAds.utils.clearPerfMarks()`
Clear entire groups of performance marks created during previous ad loading cycles by some `setupMetrics()` configuration. This is specially useful in websites that behave like single-page applications and don’t automatically clear the browser’s performance entry buffer very often.

javascript
oAds.utils.clearPerfMarks(eventDefArray, groupsToClear)

- `eventDefArray` **(required)** `<Array>` - An array of metrics groups expected to have the same structure as defined in [setupMetrics()](#oadsutilssetupmetrics).
- `groupsToClear` **(required)** `<Array>` - An array of metrics groups whose associated performance marks we want to remove.

### `clearPerMarks()` Example:

javascript
const metricsDefinitions = … // as per the 'setupMetrics' example

// Clear all existing performance marks defined in the 'slot-rendered' and 'slot-rendered' groups
oAds.utils.clearPerfMarks(metricsDefinitions, ['slot-requested', 'slot-rendered']);
`` With the previously definedmetricsDefinitionsarray, this code will remove allslotReady,slotCanRender,slotGoRender,slotRenderStart,slotExpandandslotRenderEnded` existing marks

Misc

Changing behaviour based on which ad loads {#ads-loaded}

All ads get an attribute added called data-o-ads-loaded, which contains the format of the ad that loaded. For example, data-o-ads-loaded="Billboard".

A product can use this to change the styles based on which ad has loaded (for example, to increase the height of a reserved slot if a larger ad loads).

Developing

Install & Demos

Tests

See the test documentation

Releasing

You will need a GITHUB_TOKEN environment variable with access to the repository in your .env file
Get a github token with "repo" access and make it accessible as an environment variable.

Run npm run release (patch|minor|major|x.y.z) in master then follow the interactive steps.

This will bump version numbers in the source and commit them, push to github and create a new release.

The command uses release-it under the hood as well as genversion to automatically bump version numbers in the source.

Migration

See the migration guide

Support Status
active
Switch component view

GitHub Repository

Install o-ads

If using the Build Service, add o-ads@^18.3.0 to your script and link tags.

If running a Manual Build, run bower install --save "o-ads@^18.3.0".

Help & Support

o-ads is not supported directly by the Origami team. We make no guarantees, but will help if we can. First try contacting its maintainers at:

Slack: #advertising-dev
Email: origami.advertising.technology@ft.com