       if typeof @options.loading is 'function'
         @$container.find(@options.navSelector).each(@options.loading)
 
-    _success: ->
-      # ignore any requests that started before we last invalidated
-      return if @_isInvalidatedRequest(@requestAts.shift())
-      @_recache()
+    _success: ($container) ->
+      # ignore any requests for elements that are no longer on the page
+      return unless $.contains(document, $container[0])
       @options.state.loading = false
       @_log "New page loaded!"
       if typeof @options.success is 'function'
-        @$container.find(@options.navSelector).each(@options.success)
+        $container.find(@options.navSelector).each(@options.success)
 
-    _error: ->
-      # ignore any requests that started before we last invalidated
-      return if @_isInvalidatedRequest(@requestAts.shift())
+    _error: ($container) ->
+      # ignore any requests for elements that are no longer on the page
+      return unless $.contains(document, $container[0])
       @options.state.loading = false
       @_log "Error loading new page :("
       if typeof @options.error is 'function'
-        @$container.find(@options.navSelector).each(@options.error)
+        $container.find(@options.navSelector).each(@options.error)
 
     # Pause firing of events on scroll
     pause: ->

      else
        @_loading()

        @requestAts.push +new Date # note when this request started
        $.getScript(@$container.find(@options.navSelector).attr('href'))
          .done(=> @_success())
          .fail(=> @_error())

    _loading: ->
      @options.state.loading = true

      @check()

    _recache: ->
      # remove the existing scroll listener
      @$context.off("scroll")
      
      # Recache the element references we use (needed when using turbolinks)
      @$container = $("[data-jquery-infinite-pages-container=#{@instanceId}]")
      @$table = @$container.find('table')
      @$context = $(@options.context)

      @_listenForScrolling()
      
    _listenForScrolling: ->
      # Debounce scroll event to improve performance
      scrollDelay = 250
      scrollTimeout = null
      lastCheckAt = null
      scrollHandler = =>
        lastCheckAt = +new Date
        @check()

      # Have we waited enough time since the last check?
      shouldCheck = -> +new Date > lastCheckAt + scrollDelay

      @$context.scroll ->
        scrollHandler() if shouldCheck() # Call check once every scrollDelay ms
        if scrollTimeout
          clearTimeout(scrollTimeout)
          scrollTimeout = null
        scrollTimeout = setTimeout(scrollHandler, scrollDelay)

    _invalidateActiveRequests: ->
      # Invalidate any active requests (needed when using turbolinks)
