Permalink
Browse files

fix back and forward bug

  • Loading branch information...
1 parent aafbd92 commit a77ed74c6dd9d98ed4ea0a5d12b37d05341e0aa2 @jserme committed Mar 11, 2015
Showing with 58 additions and 24 deletions.
  1. +58 −24 _layouts/default.html
View
@@ -87,13 +87,63 @@
window.history && window.history.pushState && window.history.replaceState &&
!navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/)
+ var request = function(url, callback) {
+ var defaultJump = function() {
+ location.href = url
+ }
+
+ $.ajax({
+ url: url,
+ error: defaultJump,
+ success: function(data) {
+ try {
+ callback && callback(data)
+ } catch (e) {
+ //出错直接跳转
+ defaultJump()
+ }
+ }
+ })
+ }
+
+ var getContent = function(data, opts) {
+ var body = data.match(opts.contentReg || /<body>[\s\r\n]+([\s\S]+)<\/body>/i)[1]
+ var title = data.match(opts.titleReg || /<title>([\s\S]+)<\/title>[\s\r\n]+/i)[1]
+
+ return {
+ body: body,
+ title: title
+ }
+ }
+
+ var setContent = function(content, opts) {
+ $(opts.container).html(content.body)
+ document.title = content.title
+ }
+
+ var pushState = function(state) {
+ history.pushState(state, state.title, state.url)
+ }
+
$.fn.ajaxLoadPage = function(opts) {
var context = this
if (!support) {
return this
}
+ $(window).on('popstate', function(event) {
+ var state = event.originalEvent.state
+ if (!state) {
+ return
+ }
+ request(state.url, function(data) {
+ var content = getContent(data, opts)
+ setContent(content, opts)
+ opts.callback && opts.callback()
+ })
+ })
+
return this.on('click', opts.selector || 'a', function(event) {
if (!opts.container) {
opts.container = context
@@ -108,30 +158,14 @@
event.preventDefault()
var url = link.href
-
- var defaultJump = function() {
- location.href = url
- }
-
- $.ajax({
- url: url,
- error: defaultJump,
- success: function(data) {
- try {
- var body = data.match(opts.contentReg || /<body>[\s\r\n]+([\s\S]+)<\/body>/i)[1]
- var title = data.match(opts.titleReg || /<title>([\s\S]+)<\/title>[\s\r\n]+/i)[1]
-
- $(opts.container).html(body)
- document.title = title
- history.pushState({}, title, url)
-
- opts.callback && opts.callback()
- } catch (e) {
- console.log(e)
- //出错直接跳转
- //defaultJump()
- }
- }
+ request(url, function(data) {
+ var content = getContent(data, opts)
+ setContent(content, opts)
+ pushState({
+ url: url,
+ title: content.title
+ })
+ opts.callback && opts.callback()
})
})
}

0 comments on commit a77ed74

Please sign in to comment.