forked from coop182/jquery.dfp.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.dfp.js
519 lines (396 loc) · 17.1 KB
/
jquery.dfp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/**
* jQuery DFP v1.0.18
* http://github.com/coop182/jquery.dfp.js
*
* Copyright 2013 Matt Cooper
* Released under the MIT license
*/
(function ($, window, undefined) {
"use strict";
var
// Save Scope
dfpScript = this,
// DFP account ID
dfpID = '',
// Count of ads
count = 0,
// Count of rendered ads
rendered = 0,
// Default DFP selector
dfpSelector = '.adunit',
// DFP options object
dfpOptions = {},
// Keep track of if we've already tried to load gpt.js before
dfpIsLoaded = false,
// Collection of ads
$adCollection,
// Store adunit on div as:
storeAs = 'googleAdUnit',
/**
* Init function sets required params and loads Google's DFP script
* @param String id The DFP account ID
* @param String selector The adunit selector
* @param Object options Custom options to apply
*/
init = function (id, selector, options) {
dfpID = id;
$adCollection = $(selector);
dfpLoader();
setOptions(options);
$(function () {
createAds();
displayAds();
});
},
/**
* Set the options for DFP
* @param Object options Custom options to apply
*/
setOptions = function (options) {
// Set default options
dfpOptions = {
setTargeting: {},
setCategoryExclusion: '',
setLocation: '',
enableSingleRequest: true,
collapseEmptyDivs: 'original',
refreshExisting: true,
disablePublisherConsole: false,
disableInitialLoad: false,
noFetch: false
};
if (typeof (options.setUrlTargeting) == 'undefined' || options.setUrlTargeting)
{
// Get URL Targeting
var urlTargeting = getUrlTargeting();
$.extend(true, dfpOptions.setTargeting, { inURL: urlTargeting.inURL, URLIs: urlTargeting.URLIs, Query: urlTargeting.Query, Domain: window.location.host });
}
// Merge options objects
$.extend(true, dfpOptions, options);
// If a custom googletag is specified, use it.
if (dfpOptions.googletag) {
window.googletag.cmd.push(function () {
$.extend(true, window.googletag, dfpOptions.googletag);
});
}
},
/**
* Find and create all Ads
* @return Array an array of ad units that have been created.
*/
createAds = function () {
// Loops through on page Ad units and gets ads for them.
$adCollection.each(function () {
var $adUnit = $(this);
count++;
// adUnit name
var adUnitName = getName($adUnit);
// adUnit id - this will use an existing id or an auto generated one.
var adUnitID = getID($adUnit, adUnitName, count);
// get dimensions of the adUnit
var dimensions = getDimensions($adUnit);
// get existing content
var $existingContent = $adUnit.html();
// wipe html clean ready for ad and set the default display class.
$adUnit.html('').addClass('display-none');
// Push commands to DFP to create ads
window.googletag.cmd.push(function () {
var googleAdUnit,
$adUnitData = $adUnit.data(storeAs);
if ($adUnitData) {
// Get existing ad unit
googleAdUnit = $adUnitData;
} else {
// Create the ad - out of page or normal
if ($adUnit.data('outofpage')) {
googleAdUnit = window.googletag.defineOutOfPageSlot('/' + dfpID + '/' + adUnitName, adUnitID).addService(window.googletag.pubads());
} else {
googleAdUnit = window.googletag.defineSlot('/' + dfpID + '/' + adUnitName, dimensions, adUnitID).addService(window.googletag.pubads());
}
}
// Sets custom targeting for just THIS ad unit if it has been specified
var targeting = $adUnit.data("targeting");
if (targeting) {
$.each(targeting, function (k, v) {
googleAdUnit.setTargeting(k, v);
});
}
// Sets custom exclusions for just THIS ad unit if it has been specified
var exclusions = $adUnit.data("exclusions");
if (exclusions) {
var exclusionsGroup = exclusions.split(',');
var valueTrimmed;
$.each(exclusionsGroup, function (k, v) {
valueTrimmed = $.trim(v);
if (valueTrimmed.length > 0) {
googleAdUnit.setCategoryExclusion(valueTrimmed);
}
});
}
// The following hijacks an internal google method to check if the div has been
// collapsed after the ad has been attempted to be loaded.
googleAdUnit.oldRenderEnded = googleAdUnit.oldRenderEnded || googleAdUnit.renderEnded;
googleAdUnit.renderEnded = function () {
rendered++;
var display = $adUnit.css('display');
// if the div has been collapsed but there was existing content expand the
// div and reinsert the existing content.
if (display === 'none' && $.trim($existingContent).length > 0 && dfpOptions.collapseEmptyDivs === 'original') {
$adUnit.show().html($existingContent);
display = 'block display-original';
}
$adUnit.removeClass('display-none').addClass('display-' + display);
googleAdUnit.oldRenderEnded();
// Excute afterEachAdLoaded callback if provided
if (typeof dfpOptions.afterEachAdLoaded === 'function') {
dfpOptions.afterEachAdLoaded.call(this, $adUnit);
}
// Excute afterAllAdsLoaded callback if provided
if (typeof dfpOptions.afterAllAdsLoaded === 'function' && rendered === count) {
dfpOptions.afterAllAdsLoaded.call(this, $adCollection);
}
};
// Store googleAdUnit reference
$adUnit.data(storeAs, googleAdUnit);
});
});
// Push DFP config options
window.googletag.cmd.push(function () {
if (dfpOptions.enableSingleRequest === true) {
window.googletag.pubads().enableSingleRequest();
}
$.each(dfpOptions.setTargeting, function (k, v) {
window.googletag.pubads().setTargeting(k, v);
});
if( typeof(dfpOptions.setLocation) === "object") {
if( typeof(dfpOptions.setLocation.latitude) === "number" && typeof(dfpOptions.setLocation.longitude) === "number" && typeof(dfpOptions.setLocation.precision) === "number") {
window.googletag.pubads().setLocation(dfpOptions.setLocation.latitude, dfpOptions.setLocation.longitude, dfpOptions.setLocation.precision);
} else if ( typeof(dfpOptions.setLocation.latitude) === "number" && typeof(dfpOptions.setLocation.longitude) === "number") {
window.googletag.pubads().setLocation(dfpOptions.setLocation.latitude, dfpOptions.setLocation.longitude);
}
}
if (dfpOptions.setCategoryExclusion.length > 0) {
var exclusionsGroup = dfpOptions.setCategoryExclusion.split(',');
var valueTrimmed;
$.each(exclusionsGroup, function (k, v) {
valueTrimmed = $.trim(v);
if (valueTrimmed.length > 0) {
window.googletag.pubads().setCategoryExclusion(valueTrimmed);
}
});
}
if (dfpOptions.collapseEmptyDivs === true || dfpOptions.collapseEmptyDivs === 'original') {
window.googletag.pubads().collapseEmptyDivs();
}
if (dfpOptions.disablePublisherConsole === true) {
window.googletag.pubads().disablePublisherConsole();
}
if (dfpOptions.disableInitialLoad === true) {
window.googletag.pubads().disableInitialLoad();
}
if (dfpOptions.noFetch === true) {
window.googletag.pubads().noFetch();
}
window.googletag.enableServices();
});
},
/**
* Display all created Ads
*/
displayAds = function () {
// Display each ad
$adCollection.each(function () {
var $adUnit = $(this),
$adUnitData = $adUnit.data(storeAs);
if (dfpOptions.refreshExisting && $adUnitData && $adUnit.hasClass('display-block')) {
window.googletag.cmd.push(function () { window.googletag.pubads().refresh([$adUnitData]); });
} else {
window.googletag.cmd.push(function () { window.googletag.display($adUnit.attr('id')); });
}
});
},
/**
* Create an array of paths so that we can target DFP ads to Page URI's
* @return Array an array of URL parts that can be targeted.
*/
getUrlTargeting = function () {
// Get the paths for targeting against
var paths = window.location.pathname.replace(/\/$/, ''),
patt = new RegExp('\/([^\/]*)', 'ig'),
pathsMatches = paths.match(patt),
targetPaths = ['/'],
longestpath = '';
if (pathsMatches && paths !== '/') {
var target = '',
size = pathsMatches.length;
if (size > 0) {
for (var i = 0; i < size; i++) {
target = pathsMatches[i];
targetPaths.push(target);
for (var j = i + 1; j < size; j++) {
target += pathsMatches[j];
targetPaths.push(target);
}
if (i === 0) {
targetPaths.splice(-1, 1);
longestpath = target;
}
}
}
targetPaths.push(longestpath);
}
targetPaths = targetPaths.reverse();
// Get the query params for targeting against
var url = window.location.toString().replace(/\=/ig, ':').match(/\?(.+)$/),
params = RegExp.$1.split("&");
return {
inURL: targetPaths,
URLIs: targetPaths[0],
Query: params
};
},
/**
* Get the id of the adUnit div or generate a unique one.
* @param Object $adUnit The adunit to work with
* @param String adUnitName The name of the adunit
* @param Integer count The current count of adunit, for uniqueness
* @return String The ID of the adunit or a unique autogenerated ID
*/
getID = function ($adUnit, adUnitName, count) {
return $adUnit.attr('id') || $adUnit.attr('id', adUnitName + '-auto-gen-id-' + count).attr('id');
},
/**
* Get the name of the Ad unit, either use the div id or
* check for the optional attribute data-adunit
* @param Object $adUnit The adunit to work with
* @return String The name of the adunit, will be the same as inside DFP
*/
getName = function ($adUnit) {
return $adUnit.data('adunit') || $adUnit.attr('id');
},
/**
* Get the dimensions of the ad unit using the container div dimensions or
* check for the optional attribute data-dimensions
* @param Object $adUnit The adunit to work with
* @return Array The dimensions of the adunit (width, height)
*/
getDimensions = function ($adUnit) {
var dimensions = [],
dimensionsData = $adUnit.data('dimensions');
// Check if data-dimensions are specified. If they aren't, use the dimensions of the ad unit div.
if (dimensionsData) {
var dimensionGroups = dimensionsData.split(',');
$.each(dimensionGroups, function (k, v) {
var dimensionSet = v.split('x');
dimensions.push([parseInt(dimensionSet[0], 10), parseInt(dimensionSet[1], 10)]);
});
} else {
dimensions.push([$adUnit.width(), $adUnit.height()]);
}
return dimensions;
},
/**
* Call the google DFP script - there is a little bit of error detection in here to detect
* if the dfp script has failed to load either through an error or it being blocked by an ad
* blocker... if it does not load we execute a dummy script to replace the real DFP.
*/
dfpLoader = function () {
// make sure we don't load gpt.js multiple times
dfpIsLoaded = dfpIsLoaded || $('script[src*="googletagservices.com/tag/js/gpt.js"]').length;
if (dfpIsLoaded) {
return;
}
window.googletag = window.googletag || {};
window.googletag.cmd = window.googletag.cmd || [];
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
// Adblock blocks the load of Ad scripts... so we check for that
gads.onerror = function () {
dfpBlocked();
};
var useSSL = 'https:' === document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
// Adblock plus seems to hide blocked scripts... so we check for that
if (gads.style.display === 'none') {
dfpBlocked();
}
},
/**
* This function gets called if DFP has been blocked by an adblocker
* it implements a dummy version of the dfp object and allows the script to excute its callbacks
* regardless of whether DFP is actually loaded or not... it is basically only useful for situations
* where you are laying DFP over existing content and need to init things like slide shows after the loading
* is completed.
*/
dfpBlocked = function () {
// Get the stored dfp commands
var commands = window.googletag.cmd;
// SetTimeout is a bit dirty but the script does not execute in the correct order without it
setTimeout(function () {
var _defineSlot = function(name, dimensions, id, oop) {
window.googletag.ads.push(id);
window.googletag.ads[id] = {
renderEnded: function() { },
addService: function() { return this; }
};
return window.googletag.ads[id];
};
// overwrite the dfp object - replacing the command array with a function and defining missing functions
window.googletag = {
cmd: {
push: function (callback) {
callback.call(dfpScript);
}
},
ads: [],
pubads: function () { return this; },
noFetch:function () { return this; },
disableInitialLoad: function () { return this; },
disablePublisherConsole: function () { return this; },
enableSingleRequest: function () { return this; },
setTargeting: function () { return this; },
collapseEmptyDivs: function () { return this; },
enableServices: function () { return this; },
defineSlot: function(name, dimensions, id) {
return _defineSlot(name, dimensions, id, false);
},
defineOutOfPageSlot: function (name, id) {
return _defineSlot(name, [], id, true);
},
display: function (id) {
window.googletag.ads[id].renderEnded.call(dfpScript);
return this;
}
};
// Execute any stored commands
$.each(commands, function (k, v) {
window.googletag.cmd.push(v);
});
}, 50);
};
/**
* Add function to the jQuery / Zepto / tire namespace
* @param String id (Optional) The DFP account ID
* @param Object options (Optional) Custom options to apply
*/
$.dfp = $.fn.dfp = function (id, options) {
options = options || {};
if (id === undefined) {
id = dfpID;
}
if (typeof id === 'object') {
options = id;
id = options.dfpID || dfpID;
}
var selector = this;
if (typeof this === 'function') {
selector = dfpSelector;
}
init(id, selector, options);
return this;
};
})(window.jQuery || window.Zepto || window.tire, window);