Skip to content

Instantly share code, notes, and snippets.

@kinopyo
Last active December 28, 2018 00:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kinopyo/8271d61d979247b7f9a7c43e5cd4f910 to your computer and use it in GitHub Desktop.
Save kinopyo/8271d61d979247b7f9a7c43e5cd4f910 to your computer and use it in GitHub Desktop.
Make Turbolinks work with DoubleClick for Publishers(alternative of Google Adsense)
<script type='text/javascript'>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
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);
})();
</script>
<head>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<% # Don't have to be before the application.js %>
<%= render 'layouts/google_ad' %>
</head>
//= require jquery
//= require jquery.turbolinks
//= require turbolinks
//= require_tree .
gem 'turbolinks'
gem 'jquery-turbolinks'
# credit to http://reed.github.io/turbolinks-compatibility/doubleclick_for_publishers.html
class @Gpt
constructor: ->
@slots = {}
window.googletag = googletag || {}
window.googletag.cmd = googletag.cmd || []
$(document).on 'page:fetch', => @clearAds()
$(document).on 'page:load', => @evaluate()
@evaluate()
evaluate: ->
for slot in $('.gpt-ad')
$slot = $(slot)
cachedSlot = @slots[$slot.data('gpt-div-id')]
if cachedSlot? then @refreshSlot(cachedSlot) else @defineSlot($slot)
defineSlot: ($slot) ->
divId = $slot.attr('id') # this is the part modified from orignal code
path = $slot.data('gpt-path')
dimensions = $slot.data('gpt-dimensions')
googletag.cmd.push =>
slot = googletag.defineSlot(path, dimensions, divId).addService(googletag.pubads())
googletag.enableServices()
googletag.display(divId)
@slots[divId] = slot
refreshSlot: (slot) ->
googletag.cmd.push ->
googletag.pubads().refresh([slot])
clearAds: ->
googletag.cmd.push ->
googletag.pubads().clear()
$ ->
@gpt ||= new Gpt()
<!--
The original code snippet you would get from DoubleClick for Publishers may look this:
googletag.defineSlot('/123456/ad_unit_name', [336, 280], 'div-gpt-ad-123456789-0').addService(googletag.pubads());
Map the arguments to data-gpt-path, data-gpt-dimensions and id.
Note that you need to use the "id", not "data-gpt-div-id" as the original code provided in http://reed.github.io/turbolinks-compatibility/doubleclick_for_publishers.html
-->
<div class="gpt-ad" id="div-gpt-ad-123456789-0" data-gpt-path="/123456/ad_unit_name" data-gpt-dimensions="[336, 280]"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment