relevantDigital.loadPrebid()

loadPrebid() is used for triggering Prebid/Amazon auctions and/or ad server requests when using HBM. We also cover Bid caching at the end of the article

This function works by checking all available ad slots on the page, match them to the right placement set up in Relevant Yield and then run a Prebid auction for these placements followed by an ad requests. "Ad slots" are different data-structures depending on the ad server used:

Notice: When references to slot is made in this documentation and in our JS-objects, it will only be the adserver-created slot object in the case of Google Ad Manager (when not using delayedAdserverLoading). For other ad-servers this will instead be objects created by us with a minimal but similar API.

Ad slots can be created in two ways, either:

  • Using the normal ad server functionality (googletag.defineSlot() etc). 
  • By adding <div> elements with the data-ad-unit-id attribute where the value is the id/path of the placement in the ad server. To make this work you need to set the manageAdserver parameter in the call to loadPrebid(). One advantage of this method is that the same dimensions/sizes that is specified in Yield will be used when our code defines the slots. Example:
<!-- Google Ad Manager example, value should be the ad unit path -->
<div data-ad-unit-id="/12345/news/top_banner"></div>
<!-- Xandr example, value should be tag id or inventory code -->
<div data-ad-unit-id="1234567"></div>

Amazon UAM/TAM

Relevant Yield also supports Amazon. In case any of the loaded placements are configured to use Amazon, then a separate call to Amazon will be done in parallel with the Prebid auction. In this document a "Prebid auction" refers to all headerbidding auctions, including Prebid and/or Amazon.

When/how to call loadPrebid()

This function can be called any number of times on the same page-view and the behavior (which placements that will be loaded) depends on the noSlotReload and allowedDivIds parameters.

  • For lazy-loading and infinite scroll scenarios use noSlotReload: true in order to only load new slots that has been created since the previous call to loadPrebid().
  • To reload slots that has already been loaded with loadPrebid() - use noSlotReload: false (default)
  • To filter out which slots to load, use the allowedDivIds parameter.

WARNING: Make sure to not call loadPrebid() multiple times unnecessarily for placements that becomes visible at the same time - in particular on page load. This will "queue" the Prebid auctions after each other which will cause unnecessary delays.
Let's for example say that a Prebid auction takes 0.5 seconds there are 2 slots visible immediately when entering the page. If you first call loadPrebid() when only the first slot is available and then again when the second one is available - then the ad-request for the second slot will be done after 0.5+0.5=1 seconds instead of just 0.5 seconds.
The alternative would be to first create the slots (manually or automatically by data-ad-unit-id), and then do a single call to loadPrebid().

Placements without Headerbidding

In case some of your placements are not using Prebid (for example a top banner where you don't want to wait for Prebid) - please group these slots together in a single call to loadPrebid() that is done before loading the other placements. This way the ad-request will be done immediately for these placements without the need to wait for any Prebid auction to finish. Example:

// First, load non-Prebid placements
relevantDigital.loadPrebid({ ..., allowedDivIds: ['top-banner', 'interstitial'] });

// Then load the rest, use 'noSlotReload' to avoid reloading the 2 placements again.
relevantDigital.loadPrebid({ ..., noSlotReload: true);

Accessing data from placement tag fields

If you've created placement tag fields in order to edit custom data fields per placement in Yield, then this data is accessible via AdUnit.data - where AdUnit is the representation of a placement in Relevant Yield. One way to access this data is by using the onSlotAndUnit callback. Example (using an imaginary placement tag field named "makeTransparent"):

relevantDigital.loadPrebid({
   ...
 onSlotAndUnit: ({ slot, unit }) => {
   if(unit.data.makeTransparent) {
document.getElementById(slot.getSlotElementId()).style.opacity = 0.2;
}
 },
};

Adding global callbacks

To add global callbacks, instead of supplying them to loadPrebid() - please use relevantDigital.addAuctionCallbacks().

Example usage (Google Ad Manager)

<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
<script async src="https://customer-cdn.relevant-digital.com/static/tags/62653f566896d3a9770e8187.js"></script>

<div data-ad-unit-id="/12345/news/top_banner"></div>

<script>
    (function() {
        window.relevantDigital = window.relevantDigital || {};
        relevantDigital.cmd = relevantDigital.cmd || [];
        relevantDigital.cmd.push(function() {
            relevantDigital.loadPrebid({
              configId: '62614c23e1275192580e818a',
                manageAdserver: true,
                collapseEmptyDivs: true,
            noGpt: true,
          });
        });
    })();
</script>

Obtaining script-URL and configId

The URL to the script along with the mandatory configId parameter is available in Yield via the Prebid configurations menu for the site.

script2

Parameters

configId

The configId string of the Prebid Configuration created in Yield. To list available prebid configurations you can use the relevantDigital.getConfigs() function. This parameter is mandatory.

manageAdserver

If true then new ad-slots will be constructed for every <div> with data-ad-unit-id set to the id/path of an ad placement. In addition, "setup" of the ad server will occur:

noSlotReload

If true, then slots that have already been loaded won't be reloaded. This parameter should be set in lazy-load and infinite-scroll scenarios. In fact it might be used in all cases except when you explicitly want ads to reload.

allowedDivIds

An array of div-ids for ad slots that should be loaded. Notice that this will act as a filter for which ad slots on the page that should be loaded.

*Note: This does not apply to the div attribute "data-ad-unit-id" or any other div attribute bar the id.

Example usage:

relevantDigital.loadPrebid({ ..., allowedDivIds: ['top-banner', 'interstitial'] });

allowedPlacementType

A string - "instream" or "banner". Used for loading only instream placements or only non-instream (normal) placements. This can for example be used if you don't want to combine instream placements with the rest of the placements in the prebid auction. If you want to create a different auction for instream placements that will run after the normal auction you can use this pattern:

relevantDigital.loadPrebid({ ..., allowedPlacementType: 'banner' });
relevantDigital.loadPrebid({ ..., allowedPlacementType: 'instream' });

noGpt

It is recommended to always set this to true. For legacy reasons our script will load Google's tag script gpt.js if you're using Google Ad Manager and this parameter is not true. However, for performance reasons it's usually better to load this script directly in <head> on the page instead.

delayedAdserverLoading

For Google Ad Manager - a boolean that, when set to true, makes it possible to run the Prebid auction before loading of the GAM script (gpt.js) is completed. When using this setting the slot objects in callbacks etc will not be a googletag.Slot instance. Instead it will be an own type. In order to access the actual googletag.Slot object one must wait for it to become available via the slot.waitGamSlot() function. Example: 

relevantDigital.loadPrebid({
   ...
delayedAdserverLoading: true,
 onSlotAndUnit: ({ slot, unit }) => {
slot.waitGamSlot((gamSlot) => {
gamSlot.setTargeting("some", "targeting");
});
 },
};

collapseEmptyDivs

When using Google Ad Manager and manageAdServer: true - setting this to true corresponds to setting the first parameter to true in the call to googletag.Slot.setCollapseEmptyDiv. This can also be done individually per placement by using the data-collapse-empty-divs attribute, example:

<div data-ad-unit-id="/12345/news/top_banner" data-collapse-empty-divs></div>

collapseBeforeAdFetch

When using collapseEmptyDivs (see above) setting this parameter to true corresponds to setting the second parameter to true in the call to googletag.Slot.setCollapseEmptyDiv.

This can also be done individually per placement by using the data-collapse-before-ad-fetch attribute when combined with data-collapse-empty-divs, example:

<div
data-ad-unit-id="/12345/news/top_banner"
data-collapse-empty-divs
data-collapse-before-ad-fetch
></div>

noAdsInitRequestAll

For Google Ad Manager the first ad request will by default be done by a call to googletag.pubads.refresh() without any array of slots in order to request all existing ad slots - not only the ones in the first auction. Set this parameter to true to only include slots that are part of the first auction in the first ad request (this is always the case for subsequent auctions anyway).

loadUnknownSlots

For Google Ad Manger and Xandr Ad server. Normally only slots included in the current prebid configuration is loaded - except for the first auction with Google when not using the noAdsInitRequestAll flag above. Setting this parameter to true will cause "unknown" ad slots to be loaded as well. Notice that the noSlotReload and allowedDivIds parameters will work as normal for these unknown slots.

hasSharedAdUnits

Set to true only if there are multiple placements in the same Prebid configuration that is sharing the same ad unit path in the placement ad server settings in Yield. This is a special case that also requires usage of an onSlotAndUnit callback function that returns false for some placements, as otherwise all slots will always be matched to the first placement in Yield.

WARNING: This is absolutely not the recommended way to handle shared ad unit paths in Google Ad Manger, instead when sharing ad unit paths it's recommended to to use Custom targeting key appended to ad unit path and ID of custom targeting key to append ad unit path settings in the global ad server settings in Yield. Please contact Relevant support for more details.

createAdUnitCode

Callback function for customizing the ad unit codes in Prebid.js. Notice that this code might change anyway as we're never re-using the same ad unit code. Example:

relevantDigital.loadPrebid({
   ...
   createAdUnitCode: ({ code, unit, slot }) => {
if(slot.getSlotElementId() === 'top-banner') {
return 'my-top-banner-ad-unit-code';
}
return null; // use the normal generated ad unit code
   },
};

divAttribute

A string denoting the html attribute to use instead of the default "data-ad-unit-id" when specifying ad unit path/ids with manageAdserver: true.

divToAdUnit

Callback function for implementing a custom way to match a <div data-ad-unit-id="??"> element to a placement in Yield when using manageAdserver. The callback will receive an array adUnits of all available Yield placements in the Prebid configuration to select from. Example:

relevantDigital.loadPrebid({
   ...
   divToAdUnit: ({ div, path, adUnits, auction, defaultFn }) => {
const example = div.getAttribute('data-example');
const unit = adUnits.find((unit) => unit.data.exampleField === example)
if (unit) {
return unit;
}
return defaultFn(); // use the normal procedure
   },
};

onBeforeAuctionSetup

Callback function that will be invoked before starting an auction. Example:

relevantDigital.loadPrebid({
...
onBeforeAuctionSetup: ({ auction }) => {
console.info('Relevant Yield auction object', auction);
},
};

The callback will be called when all previous auctions are done (ad requests initiated) - but before the the check for available ad-slots. Therefore you can safely create ad-slots  at this point that will be included in the auction (manually or by setting data-ad-unit-id on div-elements when using manageAdserver).

onSlotAndUnit

Callback function that will be invoked for every ad slot that will participate in the auction.  Unless the callback function returns false (exactly) - as then the ad slot will be skipped. Example:

relevantDigital.loadPrebid({
   ...
   onSlotAndUnit: ({ slot, unit, requestAuction }) => {
       console.info('Ad Slot', slot);
console.info('Prebid.JS ad unit', unit.pbAdUnit);
      console.info('Relevant Yield placement', unit);
console.info('Relevant Yield auction object', auction);
   },
};

One use-case of this callback is to do custom adjustments to the Prebid.js bid parameters, available in unit.pbAdUnit.bids[].

Notice that unit represents one placement added in Relevant Yield. If you load the same placement multiple times in the same loadPrebid() call - then multiple callbacks with the same unit will occur.

Special case: use multiple Yield placements for the same slot. This is possible by returning {reUseSlot: true}. However, this requires us to, for each slot - remove all except one ad unit instance before making the ad request. Example:

relevantDigital.loadPrebid({
onSlotAndUnit: ({ slot, unit }) => {
return { reUseSlot: true };
},
onBeforeAdRequest: ({ auction }) => {
const bySlot = new Map();
auction.usedUnitDatas.forEach((unitData) => {
bySlot[unitData.slot] = bySlot[unitData.slot] || [];
        bySlot[unitData.slot].push(unitData);
});
// Call .remove() on all ad unit instances except the one, per slot,
// that has the highest CPM bid.
const cpmOf = (unitData) => unitData.getHighestBid()?.cpm || 0;
     Object.values(bySlot).forEach((arr) => {
arr.sort((a, b) => (
cpmOf(a) === cpmOf(b) ? 0 : (cpmOf(a) < cpmOf(b) ? -1 : 1)
));
arr.slice(1).forEach((unitData) => unitData.remove());
});
},
})

onAuctionInitDone

Callback function invoked after all placements has been set up and before the Prebid.JS auction (called after onSlotAndUnit). Example:

relevantDigital.loadPrebid({
   ...
 onAuctionInitDone: ({ auction }) => {
      console.info('Relevant Yield auction object', auction);
auction.usedUnitDatas.forEach((unitData) => {
const { pbAdUnit, adUnit, slot, code } = unitData;
      console.info('Ad Slot', slot);
console.info('Prebid.JS ad unit', pbAdUnit);
console.info('Prebid.JS ad unit code', code);
    console.info('Relevant Yield placement', adUnit);
});
 },
};

onBeforeAdRequest

Callback function invoked after the Prebid auction is done and immediately before the ad request is initiated. Example:

relevantDigital.loadPrebid({
...
onBeforeAdRequest: ({ auction }) => {
console.info('Relevant Yield auction object', auction);
},
};

onAuctionDone

Callback function invoked after the Prebid auction is done and immediately after the ad request has been initiated. Example:

relevantDigital.loadPrebid({
...
onAuctionDone: ({ auction }) => {
console.info('Relevant Yield auction object', auction);
},
};

onAmazonSlot

Callback function invoked for every Amazon slot - when using Amazon UAM/TAM in parallel with Prebid. This callback can be used for "finalizing" this slot before the call to Amazon is done. Example:

relevantDigital.loadPrebid({
   ...
onAmazonSlot: (amazonSlot, unitData) => {
console.info('Ad slot, placement in Yield, etc', unitData);
amazonSlot.slotParams.SOME_KEY = "SOME_VALUE"
},
};

onAdUnitMatchingFailed

Callback when a <div data-ad-unit-id="??"> element is referring to a path that can't be found in the prebid configuration. Example:

relevantDigital.loadPrebid({
   ...
onAdUnitMatchingFailed: ({ div, auction, path, defaultFn }) => {
if (!isAnExpectedFailure(path)) { // Some kind of logic..
defaultFn(); // Default behavior (show console error)
}
},
};

pbjsCalls

This object can be used to setup functions that will intercept the calls done by Relevant Yield to the pbjs.?? functions. Currently these functions are used: 

  • requestBids
  • addAdUnits

  • removeAdUnit
  • renderAd
  • setConfig
  • aliasBidder
  • onEvent
  • getBidResponsesForAdUnitCode
  • getHighestCpmBids
  • setTargetingForGPTAsync
  • setTargetingForAst

The callback functions will get the Relevant Yield auction objects in this.auction. Example:

relevantDigital.loadPrebid({
   ...
pbjsCalls: {
  requestBids: function(requestObj) {
        console.info('Relevant Yield auction object', this.auction);        
      return pbjs.requestBids(requestObj); // Do the actual call
  },
},
};

googletagCalls

For usage with Google Ad Manager only. This object can be used to setup functions that will intercept the calls done by Relevant Yield to the googletag.?? and googletag.pubads().?? functions. Currently these functions are used:

  • addEventListener

  • removeEventListener

  • getSlots
  • defineSlot
  • disableInitialLoad

  • enableSingleRequest

  • enableServices

  • refresh

The callback functions will get the Relevant Yield auction objects in this.auction. Example:

relevantDigital.loadPrebid({
   ...
  googletagCalls: {
    defineSlot: function(adUnitPath, size, div) {
      console.info('Relevant Yield auction object', this.auction);        
      return googletag.defineSlot(adUnitPath, size, div); // Do the actual call
    },
},
};

apntagCalls

For usage with Xandr ad server only. This object can be used to setup functions that will intercept the calls done by Relevant Yield to the apntag.?? functions. Currently the functions used are these:

  • defineTag
  • loadTags
  • showTag
  • refresh
  • setKeywords
  • getTag
  • modifyTag

The callback functions will get the Relevant Yield auction objects in this.auction. Example:

relevantDigital.loadPrebid({
   ...
    apntagCalls: {
      defineTag: function(tagData) {
           console.info('Relevant Yield auction object', this.auction);
          tagData.enableSafeFrame = true; // Modify something
          return apntag.defineTag(tagData); // Do the actual call
        },
  },
};

Bid caching and createAdUnitCode

Bid Caching

Relevant yield supports Prebid Bid Caching by enabling it under the Prebid Parameters -> Generic Prebid Config Data settings.
For more information about bid caching, see https://docs.prebid.org/dev-docs/faq.html

Custom AdUnitCode

If there is a need to customise the ad unit code, define the createAdUnitCode and add it to the loadPrebid call.

Example

window.relevantDigital = window.relevantDigital || {};
relevantDigital.cmd = relevantDigital.cmd || [];
relevantDigital.cmd.push(function() {
...
relevantDigital.loadPrebid({ createAdUnitCode({params}) => 'myCustomAdUnitCode', ... }); // Will make all adUnitCodes become myCustomAdUnitCode
})

createAdUnitCode params exposes the current code, the unit and the slot, useful if you need to customise based on the units metadata:

Example

createAdUnitCode({ code, unit, slot }) => slot.getSlotElementId()

Would force the ad unit code to become the element id of the defined ad slot.

 

Other ad server specific parameters

There are some other ad server specific parameters for less common ad servers as well

  • Adform
  • Equativ (Smart)
  • Adnuntius
  • In-memory Adserver ("ad server-less")

Please send a request to Relevant support in case you need these parameters documented.