Skip to content

Instantly share code, notes, and snippets.

@dhh
Created August 19, 2013 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhh/8460cd271cc57dc361d0 to your computer and use it in GitHub Desktop.
Save dhh/8460cd271cc57dc361d0 to your computer and use it in GitHub Desktop.
diff --git a/lib/assets/javascripts/turbolinks.js.coffee b/lib/assets/javascripts/turbolinks.js.coffee
index ba202ef..4da0afa 100644
--- a/lib/assets/javascripts/turbolinks.js.coffee
+++ b/lib/assets/javascripts/turbolinks.js.coffee
@@ -10,9 +10,19 @@ createDocument = null
xhr = null
-fetchReplacement = (url) ->
+fetch = (url) ->
rememberReferer()
cacheCurrentPage()
+
+ reflectNewUrl url
+
+ if cachedPage = latestPageCacheForUrl url
+ fetchHistory cachedPage
+ fetchReplacement url, => recallScrollPosition cachedPage
+ else
+ fetchReplacement url, resetScrollPosition
+
+fetchReplacement = (url, onloadFunction) ->
triggerEvent 'page:fetch', url: url
xhr?.abort()
@@ -25,10 +35,9 @@ fetchReplacement = (url) ->
triggerEvent 'page:receive'
if doc = processResponse()
- reflectNewUrl url
changePage extractTitleAndBody(doc)...
reflectRedirectedUrl()
- resetScrollPosition()
+ onloadFunction()
triggerEvent 'page:load'
else
document.location.href = url
@@ -40,7 +49,6 @@ fetchReplacement = (url) ->
xhr.send()
fetchHistory = (cachedPage) ->
- cacheCurrentPage()
xhr?.abort()
changePage cachedPage.title, cachedPage.body
recallScrollPosition cachedPage
@@ -65,6 +73,11 @@ constrainPageCacheTo = (limit) ->
pageCache[key] = null if key <= currentState.position - limit
return
+latestPageCacheForUrl = (url) ->
+ pageCacheKeysLatestFirst = Object.keys(pageCache).sort (a, b) -> b - a
+ return pageCache[key] for key in pageCacheKeysLatestFirst when pageCache[key]?.url is url
+
+
changePage = (title, body, csrfToken, runScripts) ->
document.title = title
document.documentElement.replaceChild body, document.body
@@ -273,6 +286,7 @@ installJqueryAjaxSuccessPageUpdateTrigger = ->
installHistoryChangeHandler = (event) ->
if event.state?.turbolinks
if cachedPage = pageCache[event.state.position]
+ cacheCurrentPage()
fetchHistory cachedPage
else
visit event.target.location.href
@@ -301,7 +315,7 @@ requestMethodIsSafe =
browserSupportsTurbolinks = browserSupportsPushState and browserIsntBuggy and requestMethodIsSafe
if browserSupportsTurbolinks
- visit = fetchReplacement
+ visit = fetch
initializeTurbolinks()
else
visit = (url) -> document.location.href = url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment