reed / turbolinks-compatibility

A collection of tutorials for how to get your favorite javascript libraries, plugins, and snippets working with Turbolinks.
reed.github.io/turbolinks-compatibility
MIT License
147 stars 35 forks source link

Turbolink 5 and Google DFP not working #85

Open robypez opened 6 years ago

robypez commented 6 years ago

Hello, I'm getting crazy with Turbolink 5. I follow the "unofficial" guide

[]Turbolink on Doubleclick for publisher (http://reed.github.io/turbolinks-compatibility/doubleclick_for_publishers.html)

I have to reload the page to see advertising. I try also to change the events to

class @Gpt
  constructor: ->
    @slots = {}
    window.googletag = googletag || {}
    window.googletag.cmd = googletag.cmd || []

    $(document).on 'turbolinks:request-start', => @clearAds()
    $(document).on 'turbolinks: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: ->
    console.log 'cleared'
    googletag.cmd.push ->
      googletag.pubads().clear()

$ ->
  @gpt ||= new Gpt()

But I this error in console for every slot.

pubads_impl_246.js:1 Exception in queued GPT command TypeError: Cannot read property 'addService' of null
    at Arguments.<anonymous> (js-googledfp.self-24885bee2530e5381882edd1ae22fb247ce3c497fbdbc44b4f7831161d6209ce.js?body=1:45)
    at sn._.h.push (pubads_impl_246.js:1)
    at sn.push (pubads_impl_246.js:1)
    at ln.push (pubads_impl_246.js:1)
    at Gpt.Gpt.defineSlot (js-googledfp.self-24885bee2530e5381882edd1ae22fb247ce3c497fbdbc44b4f7831161d6209ce.js?body=1:42)
    at Gpt.Gpt.evaluate (js-googledfp.self-24885bee2530e5381882edd1ae22fb247ce3c497fbdbc44b4f7831161d6209ce.js?body=1:31)
    at HTMLDocument.<anonymous> (js-googledfp.self-24885bee2530e5381882edd1ae22fb247ce3c497fbdbc44b4f7831161d6209ce.js?body=1:14)
    at HTMLDocument.dispatch (jquery.self-06c43429d1047ce3f355da574d8a9750209971b8b1b8f264f91f5518c5fcc060.js?body=1:5207)
    at HTMLDocument.elemData.handle (jquery.self-06c43429d1047ce3f355da574d8a9750209971b8b1b8f264f91f5518c5fcc060.js?body=1:5015)
    at Object.t.dispatch (turbolinks.self-1d1fddf91adc38ac2045c51f0a3e05ca97d07d24d15a4dcbf705009106489e69.js?body=1:6)