diff --git a/jquery.dfp.js b/jquery.dfp.js index be68354..2c42ff3 100644 --- a/jquery.dfp.js +++ b/jquery.dfp.js @@ -27,596 +27,649 @@ }(function ($) { var - - // Save Scope - dfpScript = this || {}; + // Save Scope + dfpScript = this || {}; var - // DFP account ID - dfpID = '', + // DFP account ID + dfpID = '', - // Init counters - count = 0, - uid = 0, - rendered = 0, + // Init counters + count = 0, + uid = 0, + rendered = 0, - // Default DFP selector - dfpSelector = '.adunit', + // Default DFP selector + dfpSelector = '.adunit', - adsCouldNeverBeInitilized = false, + adsCouldNeverBeInitilized = false, - // Keep track of if we've already tried to load gpt.js before - dfpIsLoaded = false, + // Keep track of if we've already tried to load gpt.js before + dfpIsLoaded = false, - // Store adunit on div as: - storeAs = 'googleAdUnit', + // 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) { - var $adCollection; + /** + * 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) { + var $adCollection; - // Reset counters on each call - count = 0; - rendered = 0; + // Reset counters on each call + count = 0; + rendered = 0; - dfpID = id; - $adCollection = $(selector); + dfpID = id; + $adCollection = $(selector); - /** - * @returns {boolean} - */ - dfpScript.shouldCheckForAdBlockers = function(){ - return options ? typeof options.afterAdBlocked === 'function' : false; - }; + /** + * @returns {boolean} + */ + dfpScript.shouldCheckForAdBlockers = function () { + return options ? typeof options.afterAdBlocked === 'function' : false; + }; - // explicitly wait for loader to be completed, otherwise the googletag might not be available - dfpLoader(options, $adCollection).then(function(){ - options = setOptions(options); - dfpScript.dfpOptions = options; + // explicitly wait for loader to be completed, otherwise the googletag might not be available + dfpLoader(options, $adCollection).then(function () { + options = setOptions(options); + dfpScript.dfpOptions = options; - $(function () { - createAds(options, $adCollection); - displayAds(options, $adCollection); + $(function () { + createAds(options, $adCollection); + displayAds(options, $adCollection); + }); }); - }); - }, + }, - /** - * Set the options for DFP - * @param Object options Custom options to apply - * @return Object extended options - */ - setOptions = function (options) { - - // Set default options - var dfpOptions = { - setTargeting: {}, - setCategoryExclusion: '', - setLocation: '', - enableSingleRequest: true, - collapseEmptyDivs: 'original', - refreshExisting: true, - disablePublisherConsole: false, - disableInitialLoad: false, - setCentering: false, - noFetch: false, - namespace: undefined, - sizeMapping: {} - }; + /** + * Set the options for DFP + * @param Object options Custom options to apply + * @return Object extended options + */ + setOptions = function (options) { + + // Set default options + var dfpOptions = { + setTargeting: {}, + setCategoryExclusion: '', + setLocation: '', + enableSingleRequest: true, + collapseEmptyDivs: 'original', + refreshExisting: true, + disablePublisherConsole: false, + disableInitialLoad: false, + setCentering: false, + noFetch: false, + namespace: undefined, + sizeMapping: {} + }; - if (typeof options.setUrlTargeting === 'undefined' || options.setUrlTargeting) { - // Get URL Targeting - var urlTargeting = getUrlTargeting(options.url); - $.extend(true, dfpOptions.setTargeting, { - UrlHost: urlTargeting.Host, - UrlPath: urlTargeting.Path, - UrlQuery: urlTargeting.Query - }); - } + if (typeof options.setUrlTargeting === 'undefined' || options.setUrlTargeting) { + // Get URL Targeting + var urlTargeting = getUrlTargeting(options.url); + $.extend(true, dfpOptions.setTargeting, { + UrlHost: urlTargeting.Host, + UrlPath: urlTargeting.Path, + UrlQuery: urlTargeting.Query + }); + } - // Merge options objects - $.extend(true, dfpOptions, options); + // 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); - }); - } + // If a custom googletag is specified, use it. + if (dfpOptions.googletag) { + window.googletag.cmd.push(function () { + $.extend(true, window.googletag, dfpOptions.googletag); + }); + } - return dfpOptions; - }, + return dfpOptions; + }, - /** - * Find and create all Ads - * @param Object dfpOptions options related to ad instantiation - * @param jQuery $adCollection collection of ads - * @return Array an array of ad units that have been created. - */ - createAds = function (dfpOptions, $adCollection) { - var googletag = window.googletag; - // Loops through on page Ad units and gets ads for them. - $adCollection.each(function () { - var $adUnit = $(this); + /** + * Find and create all Ads + * @param Object dfpOptions options related to ad instantiation + * @param jQuery $adCollection collection of ads + * @return Array an array of ad units that have been created. + */ + createAds = function (dfpOptions, $adCollection) { + var googletag = window.googletag; - count++; + // Loops through on page Ad units and gets ads for them. + $adCollection.each(function () { + var $adUnit = $(this); - // adUnit name - var adUnitName = getName($adUnit, dfpOptions); + count++; - // adUnit id - this will use an existing id or an auto generated one. - var adUnitID = getID($adUnit, adUnitName); + // adUnit name + var adUnitName = getName($adUnit, dfpOptions); - // get dimensions of the adUnit - var dimensions = getDimensions($adUnit); + // adUnit id - this will use an existing id or an auto generated one. + var adUnitID = getID($adUnit, adUnitName); - // set existing content - $adUnit.data('existingContent', $adUnit.html()); + // get dimensions of the adUnit + var dimensions = getDimensions($adUnit); - // wipe html clean ready for ad and set the default display class. - $adUnit.html('').addClass('display-none'); + // set existing content + $adUnit.data('existingContent', $adUnit.html()); - // Push commands to DFP to create ads - googletag.cmd.push(function () { + // wipe html clean ready for ad and set the default display class. + $adUnit.html('').addClass('display-none'); - var googleAdUnit, - $adUnitData = $adUnit.data(storeAs); + // Push commands to DFP to create ads + googletag.cmd.push(function () { - if ($adUnitData) { + var googleAdUnit, + $adUnitData = $adUnit.data(storeAs); - // Get existing ad unit - googleAdUnit = $adUnitData; + if ($adUnitData) { - } else { + // Get existing ad unit + googleAdUnit = $adUnitData; - // Build slotName for loading - var slotName; - if (dfpID === '') { - slotName = adUnitName; } else { - slotName = '/' + dfpID + '/' + adUnitName; - } - // Create the ad - out of page or normal - if ($adUnit.data('outofpage')) { - googleAdUnit = googletag.defineOutOfPageSlot(slotName, adUnitID); - } else { - googleAdUnit = googletag.defineSlot(slotName, dimensions, adUnitID); - if ($adUnit.data('companion')) { - googleAdUnit = googleAdUnit.addService(googletag.companionAds()); + // Build slotName for loading + var slotName; + if (dfpID === '') { + slotName = adUnitName; + } else { + slotName = '/' + dfpID + '/' + adUnitName; } + + // Create the ad - out of page or normal + if ($adUnit.data('outofpage')) { + googleAdUnit = googletag.defineOutOfPageSlot(slotName, adUnitID); + } else { + googleAdUnit = googletag.defineSlot(slotName, dimensions, adUnitID); + if ($adUnit.data('companion')) { + googleAdUnit = googleAdUnit.addService(googletag.companionAds()); + } + } + + googleAdUnit = googleAdUnit.addService(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); + } + }); + } + + // Sets responsive size mapping for just THIS ad unit if it has been specified + var mapping = $adUnit.data('size-mapping'); + if (mapping && dfpOptions.sizeMapping[mapping]) { + // Convert verbose to DFP format + var map = googletag.sizeMapping(); + $.each(dfpOptions.sizeMapping[mapping], function (k, v) { + map.addSize(v.browser, v.ad_sizes); + }); + googleAdUnit.defineSizeMapping(map.build()); + } + + // Store googleAdUnit reference + $adUnit.data(storeAs, googleAdUnit); + + // Allow altering of the ad slot before ad load + if (typeof dfpOptions.beforeEachAdLoaded === 'function') { + dfpOptions.beforeEachAdLoaded.call(this, $adUnit); } + }); + + }); - googleAdUnit = googleAdUnit.addService(googletag.pubads()); + // Push DFP config options + googletag.cmd.push(function () { + var pubadsService = googletag.pubads(); + + if (dfpOptions.enableSingleRequest) { + pubadsService.enableSingleRequest(); } - // 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); - }); + $.each(dfpOptions.setTargeting, function (k, v) { + pubadsService.setTargeting(k, v); + }); + + var setLocation = dfpOptions.setLocation; + if (typeof setLocation === 'object') { + if (typeof setLocation.latitude === 'number' && typeof setLocation.longitude === 'number' && + typeof setLocation.precision === 'number') { + pubadsService.setLocation(setLocation.latitude, setLocation.longitude, setLocation.precision); + } else if (typeof setLocation.latitude === 'number' && typeof setLocation.longitude === 'number') { + pubadsService.setLocation(setLocation.latitude, setLocation.longitude); + } } - // Sets custom exclusions for just THIS ad unit if it has been specified - var exclusions = $adUnit.data('exclusions'); - if (exclusions) { - var exclusionsGroup = exclusions.split(','); + if (dfpOptions.setCategoryExclusion.length > 0) { + var exclusionsGroup = dfpOptions.setCategoryExclusion.split(','); var valueTrimmed; + $.each(exclusionsGroup, function (k, v) { valueTrimmed = $.trim(v); if (valueTrimmed.length > 0) { - googleAdUnit.setCategoryExclusion(valueTrimmed); + pubadsService.setCategoryExclusion(valueTrimmed); } }); } - // Sets responsive size mapping for just THIS ad unit if it has been specified - var mapping = $adUnit.data('size-mapping'); - if (mapping && dfpOptions.sizeMapping[mapping]) { - // Convert verbose to DFP format - var map = googletag.sizeMapping(); - $.each(dfpOptions.sizeMapping[mapping], function (k, v) { - map.addSize(v.browser, v.ad_sizes); - }); - googleAdUnit.defineSizeMapping(map.build()); + if (dfpOptions.collapseEmptyDivs) { + pubadsService.collapseEmptyDivs(); } - // Store googleAdUnit reference - $adUnit.data(storeAs, googleAdUnit); - - // Allow altering of the ad slot before ad load - if (typeof dfpOptions.beforeEachAdLoaded === 'function') { - dfpOptions.beforeEachAdLoaded.call(this, $adUnit); + if (dfpOptions.disablePublisherConsole) { + pubadsService.disablePublisherConsole(); } - }); - }); + if (dfpOptions.companionAds) { + googletag.companionAds().setRefreshUnfilledSlots(true); - // Push DFP config options - googletag.cmd.push(function () { - - var pubadsService = googletag.pubads(); - - if (dfpOptions.enableSingleRequest) { - pubadsService.enableSingleRequest(); - } - - $.each(dfpOptions.setTargeting, function (k, v) { - pubadsService.setTargeting(k, v); - }); - - var setLocation = dfpOptions.setLocation; - if (typeof setLocation === 'object') { - if (typeof setLocation.latitude === 'number' && typeof setLocation.longitude === 'number' && - typeof setLocation.precision === 'number') { - pubadsService.setLocation(setLocation.latitude, setLocation.longitude, setLocation.precision); - } else if (typeof setLocation.latitude === 'number' && typeof setLocation.longitude === 'number') { - pubadsService.setLocation(setLocation.latitude, 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) { - pubadsService.setCategoryExclusion(valueTrimmed); + if (!dfpOptions.disableInitialLoad) { + pubadsService.enableVideoAds(); } - }); - } - - if (dfpOptions.collapseEmptyDivs) { - pubadsService.collapseEmptyDivs(); - } - - if (dfpOptions.disablePublisherConsole) { - pubadsService.disablePublisherConsole(); - } - - if (dfpOptions.companionAds) { - googletag.companionAds().setRefreshUnfilledSlots(true); + } - if (!dfpOptions.disableInitialLoad) { - pubadsService.enableVideoAds(); + if (dfpOptions.disableInitialLoad) { + pubadsService.disableInitialLoad(); } - } - if (dfpOptions.disableInitialLoad) { - pubadsService.disableInitialLoad(); - } + if (dfpOptions.noFetch) { + pubadsService.noFetch(); + } - if (dfpOptions.noFetch) { - pubadsService.noFetch(); - } + if (dfpOptions.setCentering) { + pubadsService.setCentering(true); + } - if (dfpOptions.setCentering) { - pubadsService.setCentering(true); - } + if (!dfpIsLoaded) { + // Setup event listener to listen for renderEnded event and fire callbacks. + pubadsService.addEventListener('slotRenderEnded', function (event) { - // Setup event listener to listen for renderEnded event and fire callbacks. - pubadsService.addEventListener('slotRenderEnded', function (event) { + rendered++; - rendered++; + var $adUnit = $('#' + event.slot.getSlotId().getDomId()); - var $adUnit = $('#' + event.slot.getSlotId().getDomId()); + var display = event.isEmpty ? 'none' : 'block'; - var display = event.isEmpty ? 'none' : 'block'; + // if the div has been collapsed but there was existing content expand the + // div and reinsert the existing content. + var $existingContent = $adUnit.data('existingContent'); + if (display === 'none' && $.trim($existingContent).length > 0 && + dfpOptions.collapseEmptyDivs === 'original') { + $adUnit.show().html($existingContent); + display = 'block display-original'; + } - // if the div has been collapsed but there was existing content expand the - // div and reinsert the existing content. - var $existingContent = $adUnit.data('existingContent'); - 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); - $adUnit.removeClass('display-none').addClass('display-' + display); + // Excute afterEachAdLoaded callback if provided + if (typeof dfpOptions.afterEachAdLoaded === 'function') { + dfpOptions.afterEachAdLoaded.call(this, $adUnit, event); + } - // Excute afterEachAdLoaded callback if provided - if (typeof dfpOptions.afterEachAdLoaded === 'function') { - dfpOptions.afterEachAdLoaded.call(this, $adUnit, event); + // Excute afterAllAdsLoaded callback if provided + if (typeof dfpOptions.afterAllAdsLoaded === 'function' && rendered === count) { + dfpOptions.afterAllAdsLoaded.call(this, $adCollection); + } + }); } - // Excute afterAllAdsLoaded callback if provided - if (typeof dfpOptions.afterAllAdsLoaded === 'function' && rendered === count) { - dfpOptions.afterAllAdsLoaded.call(this, $adCollection); + // this will work with AdblockPlus + if (dfpScript.shouldCheckForAdBlockers() && !googletag._adBlocked_) { + setTimeout(function () { + var slots = pubadsService.getSlots ? pubadsService.getSlots() : []; + if (slots.length > 0) { + $.get(slots[0].getContentUrl()).always(function (r) { + if (r.status !== 200) { + $.each(slots, function () { + var $adUnit = $('#' + this.getSlotId().getDomId()); + dfpOptions.afterAdBlocked.call(dfpScript, $adUnit, this); + }); + } + }); + } + }, 0); } + googletag.enableServices(); }); - // this will work with AdblockPlus - if(dfpScript.shouldCheckForAdBlockers() && !googletag._adBlocked_) { - setTimeout(function () { - var slots = pubadsService.getSlots ? pubadsService.getSlots() : []; - if (slots.length > 0) { - $.get(slots[0].getContentUrl()).always(function (r) { - if (r.status !== 200) { - $.each(slots, function () { - var $adUnit = $('#' + this.getSlotId().getDomId()); - dfpOptions.afterAdBlocked.call(dfpScript, $adUnit, this); - }); - } - }); - } - }, 0); - } + }, - googletag.enableServices(); + /** + * Display all created Ads + * @param {Object} dfpOptions options related to ad instantiation + * @param {jQuery} $adCollection collection of ads + */ + displayAds = function (dfpOptions, $adCollection) { + + var googletag = window.googletag; + // Check if google adLoader can be loaded, this will work with AdBlock + if (dfpScript.shouldCheckForAdBlockers() && !googletag._adBlocked_) { + if (googletag.getVersion) { + var script = '//partner.googleadservices.com/gpt/pubads_impl_' + + googletag.getVersion() + '.js'; + $.getScript(script).always(function (r) { + if (r && r.statusText === 'error') { + $.each($adCollection, function () { + dfpOptions.afterAdBlocked.call(dfpScript, $(this)); + }); + } + }); + } - }); + } - }, + googletag.cmd.push(function () { + $adCollection.each(function () { + var $adUnit = $(this), $adUnitData = $adUnit.data(storeAs); - /** - * Display all created Ads - * @param {Object} dfpOptions options related to ad instantiation - * @param {jQuery} $adCollection collection of ads - */ - displayAds = function (dfpOptions, $adCollection) { - - var googletag = window.googletag; - // Check if google adLoader can be loaded, this will work with AdBlock - if(dfpScript.shouldCheckForAdBlockers() && !googletag._adBlocked_) { - if (googletag.getVersion) { - var script = '//partner.googleadservices.com/gpt/pubads_impl_' + - googletag.getVersion() + '.js'; - $.getScript(script).always(function (r) { - if (r && r.statusText === 'error') { - $.each($adCollection, function () { - dfpOptions.afterAdBlocked.call(dfpScript, $(this)); - }); + if (googletag._adBlocked_) { + if (dfpScript.shouldCheckForAdBlockers()) { + dfpOptions.afterAdBlocked.call(dfpScript, $adUnit); + } } - }); - } - - } - $adCollection.each(function () { + if (dfpOptions.refreshExisting && $adUnitData && $adUnit.hasClass('display-block')) { + googletag.pubads().refresh([$adUnitData]); + } else { + googletag.display($adUnit.attr('id')); + } + }); - var $adUnit = $(this), - $adUnitData = $adUnit.data(storeAs); + if (dfpOptions.disableInitialLoad) { + var $ads = $adCollection.filter(function () { + if ($(this).hasClass('display-none')) { + return $(this); + } + }).map(function () { + return $(this).data(storeAs); + }).get(); - if (googletag._adBlocked_) { - if(dfpScript.shouldCheckForAdBlockers()) { - dfpOptions.afterAdBlocked.call(dfpScript, $adUnit); + googletag.pubads().refresh($ads); } - } - if (dfpOptions.refreshExisting && $adUnitData && $adUnit.hasClass('display-block')) { + }); + }, - googletag.cmd.push(function () { googletag.pubads().refresh([$adUnitData]); }); + /** + * Refresh Ads + * @param {Object} dfpOptions options related to ad instantiation + * @param {jQuery} $adCollection collection of ads + */ + refreshAds = function () { + var $adCollection = $(this); - } else { - googletag.cmd.push(function () { googletag.display($adUnit.attr('id')); }); - } + // Reset counters on each call + count = $adCollection.length; + rendered = 0; - }); + googletag.cmd.push(function () { + var $ads = $adCollection.map(function () { + return $(this).data(storeAs); + }).get(); - }, + googletag.pubads().refresh($ads); + }); + }, - /** - * 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 (url) { + /** + * 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 (url) { - // Get the url and parse it to its component parts using regex from RFC2396 Appendix-B (https://tools.ietf.org/html/rfc2396#appendix-B) - var urlMatches = (url || window.location.toString()).match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/); - var matchedAuthority = urlMatches[4] || ''; - var matchedPath = (urlMatches[5] || '').replace(/(.)\/$/, '$1'); - var matchedQuery = urlMatches[7] || ''; + // Get the url and parse it to its component parts using regex from RFC2396 Appendix-B (https://tools.ietf.org/html/rfc2396#appendix-B) + var urlMatches = (url || window.location.toString()).match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/); + var matchedAuthority = urlMatches[4] || ''; + var matchedPath = (urlMatches[5] || '').replace(/(.)\/$/, '$1'); + var matchedQuery = urlMatches[7] || ''; - // Get the query params for targeting against - var params = matchedQuery.replace(/\=/ig, ':').split('&'); + // Get the query params for targeting against + var params = matchedQuery.replace(/\=/ig, ':').split('&'); - return { - Host: matchedAuthority, - Path: matchedPath, - Query: params - }; + return { + Host: matchedAuthority, + Path: matchedPath, + 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 - * @return String The ID of the adunit or a unique autogenerated ID - */ - getID = function ($adUnit, adUnitName) { + /** + * 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 + * @return String The ID of the adunit or a unique autogenerated ID + */ + getID = function ($adUnit, adUnitName) { - uid++; - return $adUnit.attr('id') || $adUnit.attr('id', adUnitName.replace(/[^A-z0-9]/g, '_') + '-auto-gen-id-' + uid).attr('id'); + uid++; + return $adUnit.attr('id') || $adUnit.attr('id', adUnitName.replace(/[^A-z0-9]/g, '_') + '-auto-gen-id-' + uid).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 - * @param Object dfpOptions options related to ad instantiation - * @return String The name of the adunit, will be the same as inside DFP - */ - getName = function ($adUnit, dfpOptions) { + /** + * 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 + * @param Object dfpOptions options related to ad instantiation + * @return String The name of the adunit, will be the same as inside DFP + */ + getName = function ($adUnit, dfpOptions) { - var adUnitName = $adUnit.data('adunit') || dfpOptions.namespace || $adUnit.attr('id') || ''; - if (typeof dfpOptions.alterAdUnitName === 'function') { - adUnitName = dfpOptions.alterAdUnitName.call(this, adUnitName, $adUnit); - } - return adUnitName; + var adUnitName = $adUnit.data('adunit') || dfpOptions.namespace || $adUnit.attr('id') || ''; + if (typeof dfpOptions.alterAdUnitName === 'function') { + adUnitName = dfpOptions.alterAdUnitName.call(this, adUnitName, $adUnit); + } + return adUnitName; - }, + }, - /** - * 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) { + /** + * 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'); + 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) { + // Check if data-dimensions are specified. If they aren't, use the dimensions of the ad unit div. + if (dimensionsData) { - var dimensionGroups = dimensionsData.split(','); + var dimensionGroups = dimensionsData.split(','); - $.each(dimensionGroups, function (k, v) { + $.each(dimensionGroups, function (k, v) { - var dimensionSet = v.split('x'); - dimensions.push([parseInt(dimensionSet[0], 10), parseInt(dimensionSet[1], 10)]); + var dimensionSet = v.split('x'); + dimensions.push([parseInt(dimensionSet[0], 10), parseInt(dimensionSet[1], 10)]); - }); + }); - } else { + } else { - dimensions.push([$adUnit.width(), $adUnit.height()]); + dimensions.push([$adUnit.width(), $adUnit.height()]); - } + } - return dimensions; + 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. - * - * @param {Object} options - * @param {Array} $adCollection - */ - dfpLoader = function (options, $adCollection) { + /** + * 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. + * + * @param {Object} options + * @param {Array} $adCollection + */ + dfpLoader = function (options, $adCollection) { - function execBlockEvents() { - if(dfpScript.shouldCheckForAdBlockers()) { - $.each($adCollection, function () { - options.afterAdBlocked.call(dfpScript, $(this)); - }); + function execBlockEvents() { + if (dfpScript.shouldCheckForAdBlockers()) { + $.each($adCollection, function () { + options.afterAdBlocked.call(dfpScript, $(this)); + }); + } } - } - // make sure we don't load gpt.js multiple times - dfpIsLoaded = dfpIsLoaded || $('script[src*="googletagservices.com/tag/js/gpt.js"]').length; - if (dfpIsLoaded) { - if(adsCouldNeverBeInitilized) { - execBlockEvents(); + // make sure we don't load gpt.js multiple times + dfpIsLoaded = dfpIsLoaded || $('script[src*="googletagservices.com/tag/js/gpt.js"]').length; + if (dfpIsLoaded) { + if (adsCouldNeverBeInitilized) { + execBlockEvents(); + } + return $.Deferred().resolve(); } - return $.Deferred().resolve(); - } - var loaded = $.Deferred(); + var loaded = $.Deferred(); - window.googletag = window.googletag || {}; - window.googletag.cmd = window.googletag.cmd || []; + window.googletag = window.googletag || {}; + window.googletag.cmd = window.googletag.cmd || []; - var gads = document.createElement('script'); - gads.async = true; - gads.type = 'text/javascript'; + 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(); - loaded.resolve(); - adsCouldNeverBeInitilized = true; - execBlockEvents(); - }; - - gads.onload = function() { - // this will work with ghostery: - if (!googletag._loadStarted_) { - googletag._adBlocked_ = true; + // Adblock blocks the load of Ad scripts... so we check for that + gads.onerror = function () { + dfpBlocked(); + loaded.resolve(); + adsCouldNeverBeInitilized = true; execBlockEvents(); - } - loaded.resolve(); - }; + }; - 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); + gads.onload = function () { + // this will work with ghostery: + if (!googletag._loadStarted_) { + googletag._adBlocked_ = true; + execBlockEvents(); + } + loaded.resolve(); + }; - // Adblock plus seems to hide blocked scripts... so we check for that - if (gads.style.display === 'none') { - 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); - return loaded; + // Adblock plus seems to hide blocked scripts... so we check for that + if (gads.style.display === 'none') { + dfpBlocked(); + } - }, + return loaded; - /** - * 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 () { - var googletag = window.googletag; - // Get the stored dfp commands - var commands = googletag.cmd; - - var _defineSlot = function (name, dimensions, id, oop) { - googletag.ads.push(id); - googletag.ads[id] = { - renderEnded: function () { }, - addService: function () { return this; } - }; + }, - return googletag.ads[id]; - }; + /** + * 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 () { + var googletag = window.googletag; + // Get the stored dfp commands + var commands = googletag.cmd; + + var _defineSlot = function (name, dimensions, id, oop) { + googletag.ads.push(id); + googletag.ads[id] = { + renderEnded: function () { + }, + addService: function () { + return this; + } + }; + + return googletag.ads[id]; + }; - // overwrite the dfp object - replacing the command array with a function and defining missing functions - googletag = { - cmd: { - push: function (callback) { - callback.call(dfpScript); + // overwrite the dfp object - replacing the command array with a function and defining missing functions + 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) { + googletag.ads[id].renderEnded.call(dfpScript); + return this; } - }, - 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) { - googletag.ads[id].renderEnded.call(dfpScript); - return this; - } - }; + }; - // Execute any stored commands - $.each(commands, function (k, v) { - googletag.cmd.push(v); - }); + // Execute any stored commands + $.each(commands, function (k, v) { + googletag.cmd.push(v); + }); - }; + }; + var publicMethods = { + init: init, + refreshAds: refreshAds + }; /** * Add function to the jQuery / Zepto namespace @@ -624,30 +677,30 @@ * @param Object options (Optional) Custom options to apply */ $.dfp = $.fn.dfp = function (id, options) { + var selector; - options = options || {}; - - if (id === undefined) { - id = dfpID; + // Init without arguments or using string cmd + if (id === undefined || (typeof id === 'string' && id === 'init')) { + selector = (typeof this === 'function') ? dfpSelector : this; + publicMethods.init.call(this, dfpID, selector, {}); } - - if (typeof id === 'object') { + // Init using just options + else if (typeof id === 'object') { options = id; id = options.dfpID || dfpID; - } - - var selector = this; - if (typeof this === 'function') { - selector = dfpSelector; + selector = (typeof this === 'function') ? dfpSelector : this; + publicMethods.init.call(this, id, selector, options); + } + // Any public method + else if (publicMethods[id] !== undefined) { + return publicMethods[id].apply(this, options); + } + else { + $.error('Method ' + id + ' does not exist'); } - - init(id, selector, options); return this; - }; - })); - })(window); diff --git a/jquery.dfp.min.js b/jquery.dfp.min.js index 1cea571..efcf525 100644 --- a/jquery.dfp.min.js +++ b/jquery.dfp.min.js @@ -5,4 +5,4 @@ * Copyright 2016 Matt Cooper * Released under the MIT license */ -!function(a,b){"use strict";!function(b){"function"==typeof define&&define.amd?define(["jquery"],b):b("object"==typeof exports?require("jquery"):a.jQuery||a.Zepto)}(function(c){var d=this||{},e="",f=0,g=0,h=0,i=".adunit",j=!1,k=!1,l="googleAdUnit",m=function(a,b,g){var i;f=0,h=0,e=a,i=c(b),d.shouldCheckForAdBlockers=function(){return g?"function"==typeof g.afterAdBlocked:!1},u(g,i).then(function(){g=n(g),d.dfpOptions=g,c(function(){o(g,i),p(g,i)})})},n=function(d){var e={setTargeting:{},setCategoryExclusion:"",setLocation:"",enableSingleRequest:!0,collapseEmptyDivs:"original",refreshExisting:!0,disablePublisherConsole:!1,disableInitialLoad:!1,setCentering:!1,noFetch:!1,namespace:b,sizeMapping:{}};if("undefined"==typeof d.setUrlTargeting||d.setUrlTargeting){var f=q(d.url);c.extend(!0,e.setTargeting,{UrlHost:f.Host,UrlPath:f.Path,UrlQuery:f.Query})}return c.extend(!0,e,d),e.googletag&&a.googletag.cmd.push(function(){c.extend(!0,a.googletag,e.googletag)}),e},o=function(b,g){var i=a.googletag;g.each(function(){var a=c(this);f++;var d=s(a,b),g=r(a,d),h=t(a);a.data("existingContent",a.html()),a.html("").addClass("display-none"),i.cmd.push(function(){var f,j=a.data(l);if(j)f=j;else{var k;k=""===e?d:"/"+e+"/"+d,a.data("outofpage")?f=i.defineOutOfPageSlot(k,g):(f=i.defineSlot(k,h,g),a.data("companion")&&(f=f.addService(i.companionAds()))),f=f.addService(i.pubads())}var m=a.data("targeting");m&&c.each(m,function(a,b){f.setTargeting(a,b)});var n=a.data("exclusions");if(n){var o,p=n.split(",");c.each(p,function(a,b){o=c.trim(b),o.length>0&&f.setCategoryExclusion(o)})}var q=a.data("size-mapping");if(q&&b.sizeMapping[q]){var r=i.sizeMapping();c.each(b.sizeMapping[q],function(a,b){r.addSize(b.browser,b.ad_sizes)}),f.defineSizeMapping(r.build())}a.data(l,f),"function"==typeof b.beforeEachAdLoaded&&b.beforeEachAdLoaded.call(this,a)})}),i.cmd.push(function(){var a=i.pubads();b.enableSingleRequest&&a.enableSingleRequest(),c.each(b.setTargeting,function(b,c){a.setTargeting(b,c)});var e=b.setLocation;if("object"==typeof e&&("number"==typeof e.latitude&&"number"==typeof e.longitude&&"number"==typeof e.precision?a.setLocation(e.latitude,e.longitude,e.precision):"number"==typeof e.latitude&&"number"==typeof e.longitude&&a.setLocation(e.latitude,e.longitude)),b.setCategoryExclusion.length>0){var j,k=b.setCategoryExclusion.split(",");c.each(k,function(b,d){j=c.trim(d),j.length>0&&a.setCategoryExclusion(j)})}b.collapseEmptyDivs&&a.collapseEmptyDivs(),b.disablePublisherConsole&&a.disablePublisherConsole(),b.companionAds&&(i.companionAds().setRefreshUnfilledSlots(!0),b.disableInitialLoad||a.enableVideoAds()),b.disableInitialLoad&&a.disableInitialLoad(),b.noFetch&&a.noFetch(),b.setCentering&&a.setCentering(!0),a.addEventListener("slotRenderEnded",function(a){h++;var d=c("#"+a.slot.getSlotId().getDomId()),e=a.isEmpty?"none":"block",i=d.data("existingContent");"none"===e&&c.trim(i).length>0&&"original"===b.collapseEmptyDivs&&(d.show().html(i),e="block display-original"),d.removeClass("display-none").addClass("display-"+e),"function"==typeof b.afterEachAdLoaded&&b.afterEachAdLoaded.call(this,d,a),"function"==typeof b.afterAllAdsLoaded&&h===f&&b.afterAllAdsLoaded.call(this,g)}),d.shouldCheckForAdBlockers()&&!i._adBlocked_&&setTimeout(function(){var e=a.getSlots?a.getSlots():[];e.length>0&&c.get(e[0].getContentUrl()).always(function(a){200!==a.status&&c.each(e,function(){var a=c("#"+this.getSlotId().getDomId());b.afterAdBlocked.call(d,a,this)})})},0),i.enableServices()})},p=function(b,e){var f=a.googletag;if(d.shouldCheckForAdBlockers()&&!f._adBlocked_&&f.getVersion){var g="//partner.googleadservices.com/gpt/pubads_impl_"+f.getVersion()+".js";c.getScript(g).always(function(a){a&&"error"===a.statusText&&c.each(e,function(){b.afterAdBlocked.call(d,c(this))})})}e.each(function(){var a=c(this),e=a.data(l);f._adBlocked_&&d.shouldCheckForAdBlockers()&&b.afterAdBlocked.call(d,a),f.cmd.push(b.refreshExisting&&e&&a.hasClass("display-block")?function(){f.pubads().refresh([e])}:function(){f.display(a.attr("id"))})})},q=function(b){var c=(b||a.location.toString()).match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/),d=c[4]||"",e=(c[5]||"").replace(/(.)\/$/,"$1"),f=c[7]||"",g=f.replace(/\=/gi,":").split("&");return{Host:d,Path:e,Query:g}},r=function(a,b){return g++,a.attr("id")||a.attr("id",b.replace(/[^A-z0-9]/g,"_")+"-auto-gen-id-"+g).attr("id")},s=function(a,b){var c=a.data("adunit")||b.namespace||a.attr("id")||"";return"function"==typeof b.alterAdUnitName&&(c=b.alterAdUnitName.call(this,c,a)),c},t=function(a){var b=[],d=a.data("dimensions");if(d){var e=d.split(",");c.each(e,function(a,c){var d=c.split("x");b.push([parseInt(d[0],10),parseInt(d[1],10)])})}else b.push([a.width(),a.height()]);return b},u=function(b,e){function f(){d.shouldCheckForAdBlockers()&&c.each(e,function(){b.afterAdBlocked.call(d,c(this))})}if(k=k||c('script[src*="googletagservices.com/tag/js/gpt.js"]').length)return j&&f(),c.Deferred().resolve();var g=c.Deferred();a.googletag=a.googletag||{},a.googletag.cmd=a.googletag.cmd||[];var h=document.createElement("script");h.async=!0,h.type="text/javascript",h.onerror=function(){v(),g.resolve(),j=!0,f()},h.onload=function(){googletag._loadStarted_||(googletag._adBlocked_=!0,f()),g.resolve()};var i="https:"===document.location.protocol;h.src=(i?"https:":"http:")+"//www.googletagservices.com/tag/js/gpt.js";var l=document.getElementsByTagName("script")[0];return l.parentNode.insertBefore(h,l),"none"===h.style.display&&v(),g},v=function(){var b=a.googletag,e=b.cmd,f=function(a,c,d,e){return b.ads.push(d),b.ads[d]={renderEnded:function(){},addService:function(){return this}},b.ads[d]};b={cmd:{push:function(a){a.call(d)}},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(a,b,c){return f(a,b,c,!1)},defineOutOfPageSlot:function(a,b){return f(a,[],b,!0)},display:function(a){return b.ads[a].renderEnded.call(d),this}},c.each(e,function(a,c){b.cmd.push(c)})};c.dfp=c.fn.dfp=function(a,c){c=c||{},a===b&&(a=e),"object"==typeof a&&(c=a,a=c.dfpID||e);var d=this;return"function"==typeof this&&(d=i),m(a,d,c),this}})}(window); \ No newline at end of file +!function(a,b){"use strict";!function(b){"function"==typeof define&&define.amd?define(["jquery"],b):b("object"==typeof exports?require("jquery"):a.jQuery||a.Zepto)}(function(c){var d=this||{},e="",f=0,g=0,h=0,i=".adunit",j=!1,k=!1,l="googleAdUnit",m=function(a,b,g){var i;f=0,h=0,e=a,i=c(b),d.shouldCheckForAdBlockers=function(){return g?"function"==typeof g.afterAdBlocked:!1},v(g,i).then(function(){g=n(g),d.dfpOptions=g,c(function(){o(g,i),p(g,i)})})},n=function(d){var e={setTargeting:{},setCategoryExclusion:"",setLocation:"",enableSingleRequest:!0,collapseEmptyDivs:"original",refreshExisting:!0,disablePublisherConsole:!1,disableInitialLoad:!1,setCentering:!1,noFetch:!1,namespace:b,sizeMapping:{}};if("undefined"==typeof d.setUrlTargeting||d.setUrlTargeting){var f=r(d.url);c.extend(!0,e.setTargeting,{UrlHost:f.Host,UrlPath:f.Path,UrlQuery:f.Query})}return c.extend(!0,e,d),e.googletag&&a.googletag.cmd.push(function(){c.extend(!0,a.googletag,e.googletag)}),e},o=function(b,g){var i=a.googletag;g.each(function(){var a=c(this);f++;var d=t(a,b),g=s(a,d),h=u(a);a.data("existingContent",a.html()),a.html("").addClass("display-none"),i.cmd.push(function(){var f,j=a.data(l);if(j)f=j;else{var k;k=""===e?d:"/"+e+"/"+d,a.data("outofpage")?f=i.defineOutOfPageSlot(k,g):(f=i.defineSlot(k,h,g),a.data("companion")&&(f=f.addService(i.companionAds()))),f=f.addService(i.pubads())}var m=a.data("targeting");m&&c.each(m,function(a,b){f.setTargeting(a,b)});var n=a.data("exclusions");if(n){var o,p=n.split(",");c.each(p,function(a,b){o=c.trim(b),o.length>0&&f.setCategoryExclusion(o)})}var q=a.data("size-mapping");if(q&&b.sizeMapping[q]){var r=i.sizeMapping();c.each(b.sizeMapping[q],function(a,b){r.addSize(b.browser,b.ad_sizes)}),f.defineSizeMapping(r.build())}a.data(l,f),"function"==typeof b.beforeEachAdLoaded&&b.beforeEachAdLoaded.call(this,a)})}),i.cmd.push(function(){var a=i.pubads();b.enableSingleRequest&&a.enableSingleRequest(),c.each(b.setTargeting,function(b,c){a.setTargeting(b,c)});var e=b.setLocation;if("object"==typeof e&&("number"==typeof e.latitude&&"number"==typeof e.longitude&&"number"==typeof e.precision?a.setLocation(e.latitude,e.longitude,e.precision):"number"==typeof e.latitude&&"number"==typeof e.longitude&&a.setLocation(e.latitude,e.longitude)),b.setCategoryExclusion.length>0){var j,l=b.setCategoryExclusion.split(",");c.each(l,function(b,d){j=c.trim(d),j.length>0&&a.setCategoryExclusion(j)})}b.collapseEmptyDivs&&a.collapseEmptyDivs(),b.disablePublisherConsole&&a.disablePublisherConsole(),b.companionAds&&(i.companionAds().setRefreshUnfilledSlots(!0),b.disableInitialLoad||a.enableVideoAds()),b.disableInitialLoad&&a.disableInitialLoad(),b.noFetch&&a.noFetch(),b.setCentering&&a.setCentering(!0),k||a.addEventListener("slotRenderEnded",function(a){h++;var d=c("#"+a.slot.getSlotId().getDomId()),e=a.isEmpty?"none":"block",i=d.data("existingContent");"none"===e&&c.trim(i).length>0&&"original"===b.collapseEmptyDivs&&(d.show().html(i),e="block display-original"),d.removeClass("display-none").addClass("display-"+e),"function"==typeof b.afterEachAdLoaded&&b.afterEachAdLoaded.call(this,d,a),"function"==typeof b.afterAllAdsLoaded&&h===f&&b.afterAllAdsLoaded.call(this,g)}),d.shouldCheckForAdBlockers()&&!i._adBlocked_&&setTimeout(function(){var e=a.getSlots?a.getSlots():[];e.length>0&&c.get(e[0].getContentUrl()).always(function(a){200!==a.status&&c.each(e,function(){var a=c("#"+this.getSlotId().getDomId());b.afterAdBlocked.call(d,a,this)})})},0),i.enableServices()})},p=function(b,e){var f=a.googletag;if(d.shouldCheckForAdBlockers()&&!f._adBlocked_&&f.getVersion){var g="//partner.googleadservices.com/gpt/pubads_impl_"+f.getVersion()+".js";c.getScript(g).always(function(a){a&&"error"===a.statusText&&c.each(e,function(){b.afterAdBlocked.call(d,c(this))})})}f.cmd.push(function(){if(e.each(function(){var a=c(this),e=a.data(l);f._adBlocked_&&d.shouldCheckForAdBlockers()&&b.afterAdBlocked.call(d,a),b.refreshExisting&&e&&a.hasClass("display-block")?f.pubads().refresh([e]):f.display(a.attr("id"))}),b.disableInitialLoad){var a=e.filter(function(){return c(this).hasClass("display-none")?c(this):void 0}).map(function(){return c(this).data(l)}).get();f.pubads().refresh(a)}})},q=function(){var a=c(this);f=a.length,h=0,googletag.cmd.push(function(){var b=a.map(function(){return c(this).data(l)}).get();googletag.pubads().refresh(b)})},r=function(b){var c=(b||a.location.toString()).match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/),d=c[4]||"",e=(c[5]||"").replace(/(.)\/$/,"$1"),f=c[7]||"",g=f.replace(/\=/gi,":").split("&");return{Host:d,Path:e,Query:g}},s=function(a,b){return g++,a.attr("id")||a.attr("id",b.replace(/[^A-z0-9]/g,"_")+"-auto-gen-id-"+g).attr("id")},t=function(a,b){var c=a.data("adunit")||b.namespace||a.attr("id")||"";return"function"==typeof b.alterAdUnitName&&(c=b.alterAdUnitName.call(this,c,a)),c},u=function(a){var b=[],d=a.data("dimensions");if(d){var e=d.split(",");c.each(e,function(a,c){var d=c.split("x");b.push([parseInt(d[0],10),parseInt(d[1],10)])})}else b.push([a.width(),a.height()]);return b},v=function(b,e){function f(){d.shouldCheckForAdBlockers()&&c.each(e,function(){b.afterAdBlocked.call(d,c(this))})}if(k=k||c('script[src*="googletagservices.com/tag/js/gpt.js"]').length)return j&&f(),c.Deferred().resolve();var g=c.Deferred();a.googletag=a.googletag||{},a.googletag.cmd=a.googletag.cmd||[];var h=document.createElement("script");h.async=!0,h.type="text/javascript",h.onerror=function(){w(),g.resolve(),j=!0,f()},h.onload=function(){googletag._loadStarted_||(googletag._adBlocked_=!0,f()),g.resolve()};var i="https:"===document.location.protocol;h.src=(i?"https:":"http:")+"//www.googletagservices.com/tag/js/gpt.js";var l=document.getElementsByTagName("script")[0];return l.parentNode.insertBefore(h,l),"none"===h.style.display&&w(),g},w=function(){var b=a.googletag,e=b.cmd,f=function(a,c,d){return b.ads.push(d),b.ads[d]={renderEnded:function(){},addService:function(){return this}},b.ads[d]};b={cmd:{push:function(a){a.call(d)}},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(a,b,c){return f(a,b,c,!1)},defineOutOfPageSlot:function(a,b){return f(a,[],b,!0)},display:function(a){return b.ads[a].renderEnded.call(d),this}},c.each(e,function(a,c){b.cmd.push(c)})},x={init:m,refreshAds:q};c.dfp=c.fn.dfp=function(a,d){var f;if(a===b||"string"==typeof a&&"init"===a)f="function"==typeof this?i:this,x.init.call(this,e,f,{});else if("object"==typeof a)d=a,a=d.dfpID||e,f="function"==typeof this?i:this,x.init.call(this,a,f,d);else{if(x[a]!==b)return x[a].apply(this,d);c.error("Method "+a+" does not exist")}return this}})}(window); \ No newline at end of file diff --git a/tests/SpecRunner.html b/tests/SpecRunner.html index f406053..b4918f4 100755 --- a/tests/SpecRunner.html +++ b/tests/SpecRunner.html @@ -21,6 +21,7 @@ + diff --git a/tests/spec/categoryExclusionSpec.js b/tests/spec/categoryExclusionSpec.js index bfbc041..b8f868a 100644 --- a/tests/spec/categoryExclusionSpec.js +++ b/tests/spec/categoryExclusionSpec.js @@ -132,6 +132,7 @@ describe('Category Exclusion', function () { enableSingleRequest: function () {}, setTargeting: function () {}, collapseEmptyDivs: function () {}, + addEventListener: function () {}, setCategoryExclusion: mock.setCategoryExclusion }; }; @@ -172,6 +173,7 @@ describe('Category Exclusion', function () { enableSingleRequest: function () {}, setTargeting: function () {}, collapseEmptyDivs: function () {}, + addEventListener: function () {}, setCategoryExclusion: mock.setCategoryExclusion }; }; @@ -211,6 +213,7 @@ describe('Category Exclusion', function () { enableSingleRequest: function () {}, setTargeting: function () {}, collapseEmptyDivs: function () {}, + addEventListener: function () {}, setCategoryExclusion: mock.setCategoryExclusion }; }; diff --git a/tests/spec/displayAdsSpec.js b/tests/spec/displayAdsSpec.js new file mode 100644 index 0000000..bf4fdde --- /dev/null +++ b/tests/spec/displayAdsSpec.js @@ -0,0 +1,50 @@ +describe('Display Ad units', function () { + + var cleanup = function () { + $('.adunit').remove(); + $('script[src*="gpt.js"]').remove(); + window.googletag = undefined; + }; + beforeEach(cleanup); + afterEach(cleanup); + + it('Refresh ads in single request with disable init load', function (done) { + var mock = {}; + mock.refresh = function (param) { + }; + + var dummyTag = {}; + dummyTag.pubads = function () { + return { + enableSingleRequest: function () {}, + setTargeting: function () {}, + collapseEmptyDivs: function () {}, + disableInitialLoad: function () {}, + addEventListener: function () {}, + refresh: mock.refresh + }; + }; + + dummyTag.enableServices = function () {}; + + spyOn(dummyTag, 'enableServices').and.callThrough(); + spyOn(mock, 'refresh').and.callThrough(); + + jQuery.dfp({ + dfpID: 'xxxxxxxxx', + googletag: dummyTag, + disableInitialLoad: true + }); + + waitsForAndRuns(function () { + if (typeof window.googletag.getVersion === 'function') { + return true; + } else { + return false; + } + }, function () { + expect(mock.refresh).toHaveBeenCalled(); + done(); + }, 5000); + }); +}); \ No newline at end of file diff --git a/tests/spec/loadingPhaseSpec.js b/tests/spec/loadingPhaseSpec.js index 0b294c2..e535611 100644 --- a/tests/spec/loadingPhaseSpec.js +++ b/tests/spec/loadingPhaseSpec.js @@ -47,7 +47,7 @@ describe('Loading Phase', function () { return false; } }, function () { - expect(window.googletag.getVersion()).toBeGreaterThan('23'); + expect(window.googletag.getVersion()).toBeGreaterThan(23); done(); }, 5000); }); diff --git a/tests/spec/targetingSpec.js b/tests/spec/targetingSpec.js index 37ed671..5dfcb08 100644 --- a/tests/spec/targetingSpec.js +++ b/tests/spec/targetingSpec.js @@ -18,7 +18,8 @@ describe('Targeting', function () { return { enableSingleRequest: function () {}, setTargeting: mock.setTargeting, - collapseEmptyDivs: function () {} + collapseEmptyDivs: function () {}, + addEventListener: function () {} }; }; @@ -56,7 +57,8 @@ describe('Targeting', function () { return { enableSingleRequest: function () { }, setTargeting: mock.setTargeting, - collapseEmptyDivs: function () { } + collapseEmptyDivs: function () { }, + addEventListener: function () { } }; }; @@ -91,7 +93,8 @@ describe('Targeting', function () { return { enableSingleRequest: function () {}, setTargeting: mock.setTargeting, - collapseEmptyDivs: function () {} + collapseEmptyDivs: function () {}, + addEventListener: function () {} }; };