wordpress知更鸟主题全站pjax无刷新

                      wordpress知更鸟主题全站pjax无刷新

前言

首先说明一下,不是专业的,很菜,全站pjax会弄,但是会有很多问题,有兴趣的小伙伴可以折腾完善一下哈!wordpress知更鸟主题全站pjax无刷新

教程

第一步:在header.php文件中body前引用jquery.js文件一般模版都有无需引用,如果没有自己引用一下,然后在引用jquery.pjax.js(这里我直接提供代码)注意:jquery.js需要放在jquery.pjax.js前面

 
  1. // jquery.pjax.js
  2. // copyright chris wanstrath
  3. // https://github.com/defunkt/jquery-pjax
  4.  
  5. (function($){
  6.  
  7. // When called on a container with a selector, fetches the href with
  8. // ajax into the container or with the data-pjax attribute on the link
  9. // itself.
  10. //
  11. // Tries to make sure the back button and ctrl+click work the way
  12. // you'd expect.
  13. //
  14. // Exported as $.fn.pjax
  15. //
  16. // Accepts a jQuery ajax options object that may include these
  17. // pjax specific options:
  18. //
  19. //
  20. // container - Where to stick the response body. Usually a String selector.
  21. // $(container).html(xhr.responseBody)
  22. // (default: current jquery context)
  23. // push - Whether to pushState the URL. Defaults to true (of course).
  24. // replace - Want to use replaceState instead? That's cool.
  25. //
  26. // For convenience the second parameter can be either the container or
  27. // the options object.
  28. //
  29. // Returns the jQuery object
  30. function fnPjax(selector, container, options) {
  31. var context = this
  32. return this.on('click.pjax', selector, function(event) {
  33. var opts = $.extend({}, optionsFor(container, options))
  34. if (!opts.container)
  35. opts.container = $(this).attr('data-pjax') || context
  36. handleClick(event, opts)
  37. })
  38. }
  39.  
  40. // Public: pjax on click handler
  41. //
  42. // Exported as $.pjax.click.
  43. //
  44. // event - "click" jQuery.Event
  45. // options - pjax options
  46. //
  47. // Examples
  48. //
  49. // $(document).on('click', 'a', $.pjax.click)
  50. // // is the same as
  51. // $(document).pjax('a')
  52. //
  53. // $(document).on('click', 'a', function(event) {
  54. // var container = $(this).closest('[data-pjax-container]')
  55. // $.pjax.click(event, container)
  56. // })
  57. //
  58. // Returns nothing.
  59. function handleClick(event, container, options) {
  60. options = optionsFor(container, options)
  61.  
  62. var link = event.currentTarget
  63.  
  64. if (link.tagName.toUpperCase() !== 'A')
  65. throw "$.fn.pjax or $.pjax.click requires an anchor element"
  66.  
  67. // Middle click, cmd click, and ctrl click should open
  68. // links in a new tab as normal.
  69. if ( event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey )
  70. return
  71.  
  72. // Ignore cross origin links
  73. if ( location.protocol !== link.protocol || location.hostname !== link.hostname )
  74. return
  75.  
  76. // Ignore anchors on the same page
  77. if (link.hash && link.href.replace(link.hash, '') ===
  78. location.href.replace(location.hash, ''))
  79. return
  80.  
  81. // Ignore empty anchor "foo.html#"
  82. if (link.href === location.href + '#')
  83. return
  84.  
  85. // Ignore event with default prevented
  86. if (event.isDefaultPrevented())
  87. return
  88.  
  89. var defaults = {
  90. url: link.href,
  91. container: $(link).attr('data-pjax'),
  92. target: link
  93. }
  94.  
  95. var opts = $.extend({}, defaults, options)
  96. var clickEvent = $.Event('pjax:click')
  97. $(link).trigger(clickEvent, [opts])
  98.  
  99. if (!clickEvent.isDefaultPrevented()) {
  100. pjax(opts)
  101. event.preventDefault()
  102. $(link).trigger('pjax:clicked', [opts])
  103. }
  104. }
  105.  
  106. // Public: pjax on form submit handler
  107. //
  108. // Exported as $.pjax.submit
  109. //
  110. // event - "click" jQuery.Event
  111. // options - pjax options
  112. //
  113. // Examples
  114. //
  115. // $(document).on('submit', 'form', function(event) {
  116. // var container = $(this).closest('[data-pjax-container]')
  117. // $.pjax.submit(event, container)
  118. // })
  119. //
  120. // Returns nothing.
  121. function handleSubmit(event, container, options) {
  122. options = optionsFor(container, options)
  123.  
  124. var form = event.currentTarget
  125.  
  126. if (form.tagName.toUpperCase() !== 'FORM')
  127. throw "$.pjax.submit requires a form element"
  128.  
  129. var defaults = {
  130. type: form.method.toUpperCase(),
  131. url: form.action,
  132. data: $(form).serializeArray(),
  133. container: $(form).attr('data-pjax'),
  134. target: form
  135. }
  136.  
  137. pjax($.extend({}, defaults, options))
  138.  
  139. event.preventDefault()
  140. }
  141.  
  142. // Loads a URL with ajax, puts the response body inside a container,
  143. // then pushState()'s the loaded URL.
  144. //
  145. // Works just like $.ajax in that it accepts a jQuery ajax
  146. // settings object (with keys like url, type, data, etc).
  147. //
  148. // Accepts these extra keys:
  149. //
  150. // container - Where to stick the response body.
  151. // $(container).html(xhr.responseBody)
  152. // push - Whether to pushState the URL. Defaults to true (of course).
  153. // replace - Want to use replaceState instead? That's cool.
  154. //
  155. // Use it just like $.ajax:
  156. //
  157. // var xhr = $.pjax({ url: this.href, container: '#main' })
  158. // console.log( xhr.readyState )
  159. //
  160. // Returns whatever $.ajax returns.
  161. function pjax(options) {
  162. options = $.extend(true, {}, $.ajaxSettings, pjax.defaults, options)
  163.  
  164. if ($.isFunction(options.url)) {
  165. options.url = options.url()
  166. }
  167.  
  168. var target = options.target
  169.  
  170. var hash = parseURL(options.url).hash
  171.  
  172. var context = options.context = findContainerFor(options.container)
  173.  
  174. // We want the browser to maintain two separate internal caches: one
  175. // for pjax'd partial page loads and one for normal page loads.
  176. // Without adding this secret parameter, some browsers will often
  177. // confuse the two.
  178. if (!options.data) options.data = {}
  179. options.data._pjax = context.selector
  180.  
  181. function fire(type, args) {
  182. var event = $.Event(type, { relatedTarget: target })
  183. context.trigger(event, args)
  184. return !event.isDefaultPrevented()
  185. }
  186.  
  187. var timeoutTimer
  188.  
  189. options.beforeSend = function(xhr, settings) {
  190. // No timeout for non-GET requests
  191. // Its not safe to request the resource again with a fallback method.
  192. if (settings.type !== 'GET') {
  193. settings.timeout = 0
  194. }
  195.  
  196. xhr.setRequestHeader('X-PJAX', 'true')
  197. xhr.setRequestHeader('X-PJAX-Container', context.selector)
  198.  
  199. if (!fire('pjax:beforeSend', [xhr, settings]))
  200. return false
  201.  
  202. if (settings.timeout > 0) {
  203. timeoutTimer = setTimeout(function() {
  204. if (fire('pjax:timeout', [xhr, options]))
  205. xhr.abort('timeout')
  206. }, settings.timeout)
  207.  
  208. // Clear timeout setting so jquerys internal timeout isn't invoked
  209. settings.timeout = 0
  210. }
  211.  
  212. options.requestUrl = parseURL(settings.url).href
  213. }
  214.  
  215. options.complete = function(xhr, textStatus) {
  216. if (timeoutTimer)
  217. clearTimeout(timeoutTimer)
  218.  
  219. fire('pjax:complete', [xhr, textStatus, options])
  220.  
  221. fire('pjax:end', [xhr, options])
  222. }
  223.  
  224. options.error = function(xhr, textStatus, errorThrown) {
  225. var container = extractContainer("", xhr, options)
  226.  
  227. var allowed = fire('pjax:error', [xhr, textStatus, errorThrown, options])
  228. if (options.type == 'GET' && textStatus !== 'abort' && allowed) {
  229. locationReplace(container.url)
  230. }
  231. }
  232.  
  233. options.success = function(data, status, xhr) {
  234. // If $.pjax.defaults.version is a function, invoke it first.
  235. // Otherwise it can be a static string.
  236. var currentVersion = (typeof $.pjax.defaults.version === 'function') ?
  237. $.pjax.defaults.version() :
  238. $.pjax.defaults.version
  239.  
  240. var latestVersion = xhr.getResponseHeader('X-PJAX-Version')
  241.  
  242. var container = extractContainer(data, xhr, options)
  243.  
  244. // If there is a layout version mismatch, hard load the new url
  245. if (currentVersion && latestVersion && currentVersion !== latestVersion) {
  246. locationReplace(container.url)
  247. return
  248. }
  249.  
  250. // If the new response is missing a body, hard load the page
  251. if (!container.contents) {
  252. locationReplace(container.url)
  253. return
  254. }
  255.  
  256. pjax.state = {
  257. id: options.id || uniqueId(),
  258. url: container.url,
  259. title: container.title,
  260. container: context.selector,
  261. fragment: options.fragment,
  262. timeout: options.timeout
  263. }
  264.  
  265. if (options.push || options.replace) {
  266. window.history.replaceState(pjax.state, container.title, container.url)
  267. }
  268.  
  269. // Clear out any focused controls before inserting new page contents.
  270. try {
  271. document.activeElement.blur()
  272. } catch (e) { }
  273.  
  274. if (container.title) document.title = container.title
  275.  
  276. fire('pjax:beforeReplace', [container.contents, options])
  277. context.html(container.contents)
  278.  
  279. // FF bug: Won't autofocus fields that are inserted via JS.
  280. // This behavior is incorrect. So if theres no current focus, autofocus
  281. // the last field.
  282. //
  283. // http://www.w3.org/html/wg/drafts/html/master/forms.html
  284. var autofocusEl = context.find('input[autofocus], textarea[autofocus]').last()[0]
  285. if (autofocusEl && document.activeElement !== autofocusEl) {
  286. autofocusEl.focus();
  287. }
  288.  
  289. executeScriptTags(container.scripts)
  290.  
  291. // Scroll to top by default
  292. if (typeof options.scrollTo === 'number')
  293. $(window).scrollTop(options.scrollTo)
  294.  
  295. // If the URL has a hash in it, make sure the browser
  296. // knows to navigate to the hash.
  297. if ( hash !== '' ) {
  298. // Avoid using simple hash set here. Will add another history
  299. // entry. Replace the url with replaceState and scroll to target
  300. // by hand.
  301. //
  302. // window.location.hash = hash
  303. var url = parseURL(container.url)
  304. url.hash = hash
  305.  
  306. pjax.state.url = url.href
  307. window.history.replaceState(pjax.state, container.title, url.href)
  308.  
  309. var target = $(url.hash)
  310. if (target.length) $(window).scrollTop(target.offset().top)
  311. }
  312.  
  313. fire('pjax:success', [data, status, xhr, options])
  314. }
  315.  
  316.  
  317. // Initialize pjax.state for the initial page load. Assume we're
  318. // using the container and options of the link we're loading for the
  319. // back button to the initial page. This ensures good back button
  320. // behavior.
  321. if (!pjax.state) {
  322. pjax.state = {
  323. id: uniqueId(),
  324. url: window.location.href,
  325. title: document.title,
  326. container: context.selector,
  327. fragment: options.fragment,
  328. timeout: options.timeout
  329. }
  330. window.history.replaceState(pjax.state, document.title)
  331. }
  332.  
  333. // Cancel the current request if we're already pjaxing
  334. var xhr = pjax.xhr
  335. if ( xhr && xhr.readyState < 4) {
  336. xhr.onreadystatechange = $.noop
  337. xhr.abort()
  338. }
  339.  
  340. pjax.options = options
  341. var xhr = pjax.xhr = $.ajax(options)
  342.  
  343. if (xhr.readyState > 0) {
  344. if (options.push && !options.replace) {
  345. // Cache current container element before replacing it
  346. cachePush(pjax.state.id, context.clone().contents())
  347.  
  348. window.history.pushState(null, "", stripPjaxParam(options.requestUrl))
  349. }
  350.  
  351. fire('pjax:start', [xhr, options])
  352. fire('pjax:send', [xhr, options])
  353. }
  354.  
  355. return pjax.xhr
  356. }
  357.  
  358. // Public: Reload current page with pjax.
  359. //
  360. // Returns whatever $.pjax returns.
  361. function pjaxReload(container, options) {
  362. var defaults = {
  363. url: window.location.href,
  364. push: false,
  365. replace: true,
  366. scrollTo: false
  367. }
  368.  
  369. return pjax($.extend(defaults, optionsFor(container, options)))
  370. }
  371.  
  372. // Internal: Hard replace current state with url.
  373. //
  374. // Work for around WebKit
  375. // https://bugs.webkit.org/show_bug.cgi?id=93506
  376. //
  377. // Returns nothing.
  378. function locationReplace(url) {
  379. window.history.replaceState(null, "", "#")
  380. window.location.replace(url)
  381. }
  382.  
  383.  
  384. var initialPop = true
  385. var initialURL = window.location.href
  386. var initialState = window.history.state
  387.  
  388. // Initialize $.pjax.state if possible
  389. // Happens when reloading a page and coming forward from a different
  390. // session history.
  391. if (initialState && initialState.container) {
  392. pjax.state = initialState
  393. }
  394.  
  395. // Non-webkit browsers don't fire an initial popstate event
  396. if ('state' in window.history) {
  397. initialPop = false
  398. }
  399.  
  400. // popstate handler takes care of the back and forward buttons
  401. //
  402. // You probably shouldn't use pjax on pages with other pushState
  403. // stuff yet.
  404. function onPjaxPopstate(event) {
  405. var state = event.state
  406.  
  407. if (state && state.container) {
  408. // When coming forward from a separate history session, will get an
  409. // initial pop with a state we are already at. Skip reloading the current
  410. // page.
  411. if (initialPop && initialURL == state.url) return
  412.  
  413. // If popping back to the same state, just skip.
  414. // Could be clicking back from hashchange rather than a pushState.
  415. if (pjax.state && pjax.state.id === state.id) return
  416.  
  417. var container = $(state.container)
  418. if (container.length) {
  419. var direction, contents = cacheMapping[state.id]
  420.  
  421. if (pjax.state) {
  422. // Since state ids always increase, we can deduce the history
  423. // direction from the previous state.
  424. direction = pjax.state.id < state.id ? 'forward' : 'back'
  425.  
  426. // Cache current container before replacement and inform the
  427. // cache which direction the history shifted.
  428. cachePop(direction, pjax.state.id, container.clone().contents())
  429. }
  430.  
  431. var popstateEvent = $.Event('pjax:popstate', {
  432. state: state,
  433. direction: direction
  434. })
  435. container.trigger(popstateEvent)
  436.  
  437. var options = {
  438. id: state.id,
  439. url: state.url,
  440. container: container,
  441. push: false,
  442. fragment: state.fragment,
  443. timeout: state.timeout,
  444. scrollTo: false
  445. }
  446.  
  447. if (contents) {
  448. container.trigger('pjax:start', [null, options])
  449.  
  450. if (state.title) document.title = state.title
  451. container.trigger('pjax:beforeReplace', [contents, options])
  452. container.html(contents)
  453. pjax.state = state
  454.  
  455. container.trigger('pjax:end', [null, options])
  456. } else {
  457. pjax(options)
  458. }
  459.  
  460. // Force reflow/relayout before the browser tries to restore the
  461. // scroll position.
  462. container[0].offsetHeight
  463. } else {
  464. locationReplace(location.href)
  465. }
  466. }
  467. initialPop = false
  468. }
  469.  
  470. // Fallback version of main pjax function for browsers that don't
  471. // support pushState.
  472. //
  473. // Returns nothing since it retriggers a hard form submission.
  474. function fallbackPjax(options) {
  475. var url = $.isFunction(options.url) ? options.url() : options.url,
  476. method = options.type ? options.type.toUpperCase() : 'GET'
  477.  
  478. var form = $('<form>', {
  479. method: method === 'GET' ? 'GET' : 'POST',
  480. action: url,
  481. style: 'display:none'
  482. })
  483.  
  484. if (method !== 'GET' && method !== 'POST') {
  485. form.append($('<input>', {
  486. type: 'hidden',
  487. name: '_method',
  488. value: method.toLowerCase()
  489. }))
  490. }
  491.  
  492. var data = options.data
  493. if (typeof data === 'string') {
  494. $.each(data.split('&'), function(index, value) {
  495. var pair = value.split('=')
  496. form.append($('<input>', {type: 'hidden', name: pair[0], value: pair[1]}))
  497. })
  498. } else if (typeof data === 'object') {
  499. for (key in data)
  500. form.append($('<input>', {type: 'hidden', name: key, value: data[key]}))
  501. }
  502.  
  503. $(document.body).append(form)
  504. form.submit()
  505. }
  506.  
  507. // Internal: Generate unique id for state object.
  508. //
  509. // Use a timestamp instead of a counter since ids should still be
  510. // unique across page loads.
  511. //
  512. // Returns Number.
  513. function uniqueId() {
  514. return (new Date).getTime()
  515. }
  516.  
  517. // Internal: Strips _pjax param from url
  518. //
  519. // url - String
  520. //
  521. // Returns String.
  522. function stripPjaxParam(url) {
  523. return url
  524. .replace(/\?_pjax=[^&]+&?/, '?')
  525. .replace(/_pjax=[^&]+&?/, '')
  526. .replace(/[\?&]$/, '')
  527. }
  528.  
  529. // Internal: Parse URL components and returns a Locationish object.
  530. //
  531. // url - String URL
  532. //
  533. // Returns HTMLAnchorElement that acts like Location.
  534. function parseURL(url) {
  535. var a = document.createElement('a')
  536. a.href = url
  537. return a
  538. }
  539.  
  540. // Internal: Build options Object for arguments.
  541. //
  542. // For convenience the first parameter can be either the container or
  543. // the options object.
  544. //
  545. // Examples
  546. //
  547. // optionsFor('#container')
  548. // // => {container: '#container'}
  549. //
  550. // optionsFor('#container', {push: true})
  551. // // => {container: '#container', push: true}
  552. //
  553. // optionsFor({container: '#container', push: true})
  554. // // => {container: '#container', push: true}
  555. //
  556. // Returns options Object.
  557. function optionsFor(container, options) {
  558. // Both container and options
  559. if ( container && options )
  560. options.container = container
  561.  
  562. // First argument is options Object
  563. else if ( $.isPlainObject(container) )
  564. options = container
  565.  
  566. // Only container
  567. else
  568. options = {container: container}
  569.  
  570. // Find and validate container
  571. if (options.container)
  572. options.container = findContainerFor(options.container)
  573.  
  574. return options
  575. }
  576.  
  577. // Internal: Find container element for a variety of inputs.
  578. //
  579. // Because we can't persist elements using the history API, we must be
  580. // able to find a String selector that will consistently find the Element.
  581. //
  582. // container - A selector String, jQuery object, or DOM Element.
  583. //
  584. // Returns a jQuery object whose context is `document` and has a selector.
  585. function findContainerFor(container) {
  586. container = $(container)
  587.  
  588. if ( !container.length ) {
  589. throw "no pjax container for " + container.selector
  590. } else if ( container.selector !== '' && container.context === document ) {
  591. return container
  592. } else if ( container.attr('id') ) {
  593. return $('#' + container.attr('id'))
  594. } else {
  595. throw "cant get selector for pjax container!"
  596. }
  597. }
  598.  
  599. // Internal: Filter and find all elements matching the selector.
  600. //
  601. // Where $.fn.find only matches descendants, findAll will test all the
  602. // top level elements in the jQuery object as well.
  603. //
  604. // elems - jQuery object of Elements
  605. // selector - String selector to match
  606. //
  607. // Returns a jQuery object.
  608. function findAll(elems, selector) {
  609. return elems.filter(selector).add(elems.find(selector));
  610. }
  611.  
  612. function parseHTML(html) {
  613. return $.parseHTML(html, document, true)
  614. }
  615.  
  616. // Internal: Extracts container and metadata from response.
  617. //
  618. // 1. Extracts X-PJAX-URL header if set
  619. // 2. Extracts inline <title> tags
  620. // 3. Builds response Element and extracts fragment if set
  621. //
  622. // data - String response data
  623. // xhr - XHR response
  624. // options - pjax options Object
  625. //
  626. // Returns an Object with url, title, and contents keys.
  627. function extractContainer(data, xhr, options) {
  628. var obj = {}
  629.  
  630. // Prefer X-PJAX-URL header if it was set, otherwise fallback to
  631. // using the original requested url.
  632. obj.url = stripPjaxParam(xhr.getResponseHeader('X-PJAX-URL') || options.requestUrl)
  633.  
  634. // Attempt to parse response html into elements
  635. if (/<html/i.test(data)) {
  636. var $head = $(parseHTML(data.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0]))
  637. var $body = $(parseHTML(data.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0]))
  638. } else {
  639. var $head = $body = $(parseHTML(data))
  640. }
  641.  
  642. // If response data is empty, return fast
  643. if ($body.length === 0)
  644. return obj
  645.  
  646. // If there's a <title> tag in the header, use it as
  647. // the page's title.
  648. obj.title = findAll($head, 'title').last().text()
  649.  
  650. if (options.fragment) {
  651. // If they specified a fragment, look for it in the response
  652. // and pull it out.
  653. if (options.fragment === 'body') {
  654. var $fragment = $body
  655. } else {
  656. var $fragment = findAll($body, options.fragment).first()
  657. }
  658.  
  659. if ($fragment.length) {
  660. obj.contents = $fragment.contents()
  661.  
  662. // If there's no title, look for data-title and title attributes
  663. // on the fragment
  664. if (!obj.title)
  665. obj.title = $fragment.attr('title') || $fragment.data('title')
  666. }
  667.  
  668. } else if (!/<html/i.test(data)) {
  669. obj.contents = $body
  670. }
  671.  
  672. // Clean up any <title> tags
  673. if (obj.contents) {
  674. // Remove any parent title elements
  675. obj.contents = obj.contents.not(function() { return $(this).is('title') })
  676.  
  677. // Then scrub any titles from their descendants
  678. obj.contents.find('title').remove()
  679.  
  680. // Gather all script[src] elements
  681. obj.scripts = findAll(obj.contents, 'script[src]').remove()
  682. obj.contents = obj.contents.not(obj.scripts)
  683. }
  684.  
  685. // Trim any whitespace off the title
  686. if (obj.title) obj.title = $.trim(obj.title)
  687.  
  688. return obj
  689. }
  690.  
  691. // Load an execute scripts using standard script request.
  692. //
  693. // Avoids jQuery's traditional $.getScript which does a XHR request and
  694. // globalEval.
  695. //
  696. // scripts - jQuery object of script Elements
  697. //
  698. // Returns nothing.
  699. function executeScriptTags(scripts) {
  700. if (!scripts) return
  701.  
  702. var existingScripts = $('script[src]')
  703.  
  704. scripts.each(function() {
  705. var src = this.src
  706. var matchedScripts = existingScripts.filter(function() {
  707. return this.src === src
  708. })
  709. if (matchedScripts.length) return
  710.  
  711. var script = document.createElement('script')
  712. script.type = $(this).attr('type')
  713. script.src = $(this).attr('src')
  714. document.head.appendChild(script)
  715. })
  716. }
  717.  
  718. // Internal: History DOM caching class.
  719. var cacheMapping = {}
  720. var cacheForwardStack = []
  721. var cacheBackStack = []
  722.  
  723. // Push previous state id and container contents into the history
  724. // cache. Should be called in conjunction with `pushState` to save the
  725. // previous container contents.
  726. //
  727. // id - State ID Number
  728. // value - DOM Element to cache
  729. //
  730. // Returns nothing.
  731. function cachePush(id, value) {
  732. cacheMapping[id] = value
  733. cacheBackStack.push(id)
  734.  
  735. // Remove all entires in forward history stack after pushing
  736. // a new page.
  737. while (cacheForwardStack.length)
  738. delete cacheMapping[cacheForwardStack.shift()]
  739.  
  740. // Trim back history stack to max cache length.
  741. while (cacheBackStack.length > pjax.defaults.maxCacheLength)
  742. delete cacheMapping[cacheBackStack.shift()]
  743. }
  744.  
  745. // Shifts cache from directional history cache. Should be
  746. // called on `popstate` with the previous state id and container
  747. // contents.
  748. //
  749. // direction - "forward" or "back" String
  750. // id - State ID Number
  751. // value - DOM Element to cache
  752. //
  753. // Returns nothing.
  754. function cachePop(direction, id, value) {
  755. var pushStack, popStack
  756. cacheMapping[id] = value
  757.  
  758. if (direction === 'forward') {
  759. pushStack = cacheBackStack
  760. popStack = cacheForwardStack
  761. } else {
  762. pushStack = cacheForwardStack
  763. popStack = cacheBackStack
  764. }
  765.  
  766. pushStack.push(id)
  767. if (id = popStack.pop())
  768. delete cacheMapping[id]
  769. }
  770.  
  771. // Public: Find version identifier for the initial page load.
  772. //
  773. // Returns String version or undefined.
  774. function findVersion() {
  775. return $('meta').filter(function() {
  776. var name = $(this).attr('http-equiv')
  777. return name && name.toUpperCase() === 'X-PJAX-VERSION'
  778. }).attr('content')
  779. }
  780.  
  781. // Install pjax functions on $.pjax to enable pushState behavior.
  782. //
  783. // Does nothing if already enabled.
  784. //
  785. // Examples
  786. //
  787. // $.pjax.enable()
  788. //
  789. // Returns nothing.
  790. function enable() {
  791. $.fn.pjax = fnPjax
  792. $.pjax = pjax
  793. $.pjax.enable = $.noop
  794. $.pjax.disable = disable
  795. $.pjax.click = handleClick
  796. $.pjax.submit = handleSubmit
  797. $.pjax.reload = pjaxReload
  798. $.pjax.defaults = {
  799. timeout: 650,
  800. push: true,
  801. replace: false,
  802. type: 'GET',
  803. dataType: 'html',
  804. scrollTo: 0,
  805. maxCacheLength: 20,
  806. version: findVersion
  807. }
  808. $(window).on('popstate.pjax', onPjaxPopstate)
  809. }
  810.  
  811. // Disable pushState behavior.
  812. //
  813. // This is the case when a browser doesn't support pushState. It is
  814. // sometimes useful to disable pushState for debugging on a modern
  815. // browser.
  816. //
  817. // Examples
  818. //
  819. // $.pjax.disable()
  820. //
  821. // Returns nothing.
  822. function disable() {
  823. $.fn.pjax = function() { return this }
  824. $.pjax = fallbackPjax
  825. $.pjax.enable = enable
  826. $.pjax.disable = $.noop
  827. $.pjax.click = $.noop
  828. $.pjax.submit = $.noop
  829. $.pjax.reload = function() { window.location.reload() }
  830.  
  831. $(window).off('popstate.pjax', onPjaxPopstate)
  832. }
  833.  
  834.  
  835. // Add the state property to jQuery's event object so we can use it in
  836. // $(window).bind('popstate')
  837. if ( $.inArray('state', $.event.props) < 0 )
  838. $.event.props.push('state')
  839.  
  840. // Is pjax supported by this browser?
  841. $.support.pjax =
  842. window.history && window.history.pushState && window.history.replaceState &&
  843. // pushState isn't reliable on iOS until 5.
  844. !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/)
  845.  
  846. $.support.pjax ? enable() : disable()
  847.  
  848. })(jQuery);

第二步:将以下代码放到header.php文件中body前面即可.注意请将下方代码中的[]替换为<>

 
  1. [script type=“text/javascript”]
  2. $(document).pjax(‘a’, ‘#page’, {fragment:‘#page’, timeout:8000});
  3. [/script]

然后刷新你的网站体验全站无刷新的感觉吧,其他模版依此类推

转载请留路人博客版权

原文地址