jquery.pjax.js 25 KB

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