jquery.pjax.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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. }
  256. if (container.title) document.title = container.title
  257. fire('pjax:beforeReplace', [container.contents, options], {
  258. state: pjax.state,
  259. previousState: previousState
  260. })
  261. context.html(container.contents)
  262. // FF bug: Won't autofocus fields that are inserted via JS.
  263. // This behavior is incorrect. So if theres no current focus, autofocus
  264. // the last field.
  265. //
  266. // http://www.w3.org/html/wg/drafts/html/master/forms.html
  267. var autofocusEl = context.find('input[autofocus], textarea[autofocus]').last()[0]
  268. if (autofocusEl && document.activeElement !== autofocusEl) {
  269. autofocusEl.focus();
  270. }
  271. executeScriptTags(container.scripts)
  272. var scrollTo = options.scrollTo
  273. // Ensure browser scrolls to the element referenced by the URL anchor
  274. if (hash) {
  275. var name = decodeURIComponent(hash.slice(1))
  276. var target = document.getElementById(name) || document.getElementsByName(name)[0]
  277. if (target) scrollTo = $(target).offset().top
  278. }
  279. if (typeof scrollTo == 'number') $(window).scrollTop(scrollTo)
  280. fire('pjax:success', [data, status, xhr, options])
  281. }
  282. // Initialize pjax.state for the initial page load. Assume we're
  283. // using the container and options of the link we're loading for the
  284. // back button to the initial page. This ensures good back button
  285. // behavior.
  286. if (!pjax.state) {
  287. pjax.state = {
  288. id: uniqueId(),
  289. url: window.location.href,
  290. title: document.title,
  291. container: context.selector,
  292. fragment: options.fragment,
  293. timeout: options.timeout
  294. }
  295. window.history.replaceState(pjax.state, document.title)
  296. }
  297. // Cancel the current request if we're already pjaxing
  298. abortXHR(pjax.xhr)
  299. pjax.options = options
  300. var xhr = pjax.xhr = $.ajax(options)
  301. if (xhr.readyState > 0) {
  302. if (options.push && !options.replace) {
  303. // Cache current container element before replacing it
  304. cachePush(pjax.state.id, cloneContents(context))
  305. window.history.pushState(null, "", options.requestUrl)
  306. }
  307. fire('pjax:start', [xhr, options])
  308. fire('pjax:send', [xhr, options])
  309. }
  310. return pjax.xhr
  311. }
  312. // Public: Reload current page with pjax.
  313. //
  314. // Returns whatever $.pjax returns.
  315. function pjaxReload(container, options) {
  316. var defaults = {
  317. url: window.location.href,
  318. push: false,
  319. replace: true,
  320. scrollTo: false
  321. }
  322. return pjax($.extend(defaults, optionsFor(container, options)))
  323. }
  324. // Internal: Hard replace current state with url.
  325. //
  326. // Work for around WebKit
  327. // https://bugs.webkit.org/show_bug.cgi?id=93506
  328. //
  329. // Returns nothing.
  330. function locationReplace(url) {
  331. window.history.replaceState(null, "", pjax.state.url)
  332. window.location.replace(url)
  333. }
  334. var initialPop = true
  335. var initialURL = window.location.href
  336. var initialState = window.history.state
  337. // Initialize $.pjax.state if possible
  338. // Happens when reloading a page and coming forward from a different
  339. // session history.
  340. if (initialState && initialState.container) {
  341. pjax.state = initialState
  342. }
  343. // Non-webkit browsers don't fire an initial popstate event
  344. if ('state' in window.history) {
  345. initialPop = false
  346. }
  347. // popstate handler takes care of the back and forward buttons
  348. //
  349. // You probably shouldn't use pjax on pages with other pushState
  350. // stuff yet.
  351. function onPjaxPopstate(event) {
  352. // Hitting back or forward should override any pending PJAX request.
  353. if (!initialPop) {
  354. abortXHR(pjax.xhr)
  355. }
  356. var previousState = pjax.state
  357. var state = event.state
  358. var direction
  359. if (state && state.container) {
  360. // When coming forward from a separate history session, will get an
  361. // initial pop with a state we are already at. Skip reloading the current
  362. // page.
  363. if (initialPop && initialURL == state.url) return
  364. if (previousState) {
  365. // If popping back to the same state, just skip.
  366. // Could be clicking back from hashchange rather than a pushState.
  367. if (previousState.id === state.id) return
  368. // Since state IDs always increase, we can deduce the navigation direction
  369. direction = previousState.id < state.id ? 'forward' : 'back'
  370. }
  371. var cache = cacheMapping[state.id] || []
  372. var container = $(cache[0] || state.container), contents = cache[1]
  373. if (container.length) {
  374. if (previousState) {
  375. // Cache current container before replacement and inform the
  376. // cache which direction the history shifted.
  377. cachePop(direction, previousState.id, cloneContents(container))
  378. }
  379. var popstateEvent = $.Event('pjax:popstate', {
  380. state: state,
  381. direction: direction
  382. })
  383. container.trigger(popstateEvent)
  384. var options = {
  385. id: state.id,
  386. url: state.url,
  387. container: container,
  388. push: false,
  389. fragment: state.fragment,
  390. timeout: state.timeout,
  391. scrollTo: false
  392. }
  393. if (contents) {
  394. container.trigger('pjax:start', [null, options])
  395. pjax.state = state
  396. if (state.title) document.title = state.title
  397. var beforeReplaceEvent = $.Event('pjax:beforeReplace', {
  398. state: state,
  399. previousState: previousState
  400. })
  401. container.trigger(beforeReplaceEvent, [contents, options])
  402. container.html(contents)
  403. container.trigger('pjax:end', [null, options])
  404. } else {
  405. pjax(options)
  406. }
  407. // Force reflow/relayout before the browser tries to restore the
  408. // scroll position.
  409. container[0].offsetHeight
  410. } else {
  411. locationReplace(location.href)
  412. }
  413. }
  414. initialPop = false
  415. }
  416. // Fallback version of main pjax function for browsers that don't
  417. // support pushState.
  418. //
  419. // Returns nothing since it retriggers a hard form submission.
  420. function fallbackPjax(options) {
  421. var url = $.isFunction(options.url) ? options.url() : options.url,
  422. method = options.type ? options.type.toUpperCase() : 'GET'
  423. var form = $('<form>', {
  424. method: method === 'GET' ? 'GET' : 'POST',
  425. action: url,
  426. style: 'display:none'
  427. })
  428. if (method !== 'GET' && method !== 'POST') {
  429. form.append($('<input>', {
  430. type: 'hidden',
  431. name: '_method',
  432. value: method.toLowerCase()
  433. }))
  434. }
  435. var data = options.data
  436. if (typeof data === 'string') {
  437. $.each(data.split('&'), function (index, value) {
  438. var pair = value.split('=')
  439. form.append($('<input>', {type: 'hidden', name: pair[0], value: pair[1]}))
  440. })
  441. } else if ($.isArray(data)) {
  442. $.each(data, function (index, value) {
  443. form.append($('<input>', {type: 'hidden', name: value.name, value: value.value}))
  444. })
  445. } else if (typeof data === 'object') {
  446. var key
  447. for (key in data)
  448. form.append($('<input>', {type: 'hidden', name: key, value: data[key]}))
  449. }
  450. $(document.body).append(form)
  451. form.submit()
  452. }
  453. // Internal: Abort an XmlHttpRequest if it hasn't been completed,
  454. // also removing its event handlers.
  455. function abortXHR(xhr) {
  456. if (xhr && xhr.readyState < 4) {
  457. xhr.onreadystatechange = $.noop
  458. xhr.abort()
  459. }
  460. }
  461. // Internal: Generate unique id for state object.
  462. //
  463. // Use a timestamp instead of a counter since ids should still be
  464. // unique across page loads.
  465. //
  466. // Returns Number.
  467. function uniqueId() {
  468. return (new Date).getTime()
  469. }
  470. function cloneContents(container) {
  471. var cloned = container.clone()
  472. // Unmark script tags as already being eval'd so they can get executed again
  473. // when restored from cache. HAXX: Uses jQuery internal method.
  474. cloned.find('script').each(function () {
  475. if (!this.src) jQuery._data(this, 'globalEval', false)
  476. })
  477. return [container.selector, cloned.contents()]
  478. }
  479. // Internal: Strip internal query params from parsed URL.
  480. //
  481. // Returns sanitized url.href String.
  482. function stripInternalParams(url) {
  483. url.search = url.search.replace(/([?&])(_pjax|_)=[^&]*/g, '')
  484. return url.href.replace(/\?($|#)/, '$1')
  485. }
  486. // Internal: Parse URL components and returns a Locationish object.
  487. //
  488. // url - String URL
  489. //
  490. // Returns HTMLAnchorElement that acts like Location.
  491. function parseURL(url) {
  492. var a = document.createElement('a')
  493. a.href = url
  494. return a
  495. }
  496. // Internal: Return the `href` component of given URL object with the hash
  497. // portion removed.
  498. //
  499. // location - Location or HTMLAnchorElement
  500. //
  501. // Returns String
  502. function stripHash(location) {
  503. return location.href.replace(/#.*/, '')
  504. }
  505. // Internal: Build options Object for arguments.
  506. //
  507. // For convenience the first parameter can be either the container or
  508. // the options object.
  509. //
  510. // Examples
  511. //
  512. // optionsFor('#container')
  513. // // => {container: '#container'}
  514. //
  515. // optionsFor('#container', {push: true})
  516. // // => {container: '#container', push: true}
  517. //
  518. // optionsFor({container: '#container', push: true})
  519. // // => {container: '#container', push: true}
  520. //
  521. // Returns options Object.
  522. function optionsFor(container, options) {
  523. // Both container and options
  524. if (container && options)
  525. options.container = container
  526. // First argument is options Object
  527. else if ($.isPlainObject(container))
  528. options = container
  529. // Only container
  530. else
  531. options = {container: container}
  532. // Find and validate container
  533. if (options.container)
  534. options.container = findContainerFor(options.container)
  535. return options
  536. }
  537. // Internal: Find container element for a variety of inputs.
  538. //
  539. // Because we can't persist elements using the history API, we must be
  540. // able to find a String selector that will consistently find the Element.
  541. //
  542. // container - A selector String, jQuery object, or DOM Element.
  543. //
  544. // Returns a jQuery object whose context is `document` and has a selector.
  545. function findContainerFor(container) {
  546. container = $(container)
  547. if (!container.length) {
  548. throw "no pjax container for " + container.selector
  549. } else if (container.selector !== '' && container.context === document) {
  550. return container
  551. } else if (container.attr('id')) {
  552. return $('#' + container.attr('id'))
  553. } else {
  554. throw "cant get selector for pjax container!"
  555. }
  556. }
  557. // Internal: Filter and find all elements matching the selector.
  558. //
  559. // Where $.fn.find only matches descendants, findAll will test all the
  560. // top level elements in the jQuery object as well.
  561. //
  562. // elems - jQuery object of Elements
  563. // selector - String selector to match
  564. //
  565. // Returns a jQuery object.
  566. function findAll(elems, selector) {
  567. return elems.filter(selector).add(elems.find(selector));
  568. }
  569. function parseHTML(html) {
  570. return $.parseHTML(html, document, true)
  571. }
  572. // Internal: Extracts container and metadata from response.
  573. //
  574. // 1. Extracts X-PJAX-URL header if set
  575. // 2. Extracts inline <title> tags
  576. // 3. Builds response Element and extracts fragment if set
  577. //
  578. // data - String response data
  579. // xhr - XHR response
  580. // options - pjax options Object
  581. //
  582. // Returns an Object with url, title, and contents keys.
  583. function extractContainer(data, xhr, options) {
  584. var obj = {}, fullDocument = /<html/i.test(data)
  585. // Prefer X-PJAX-URL header if it was set, otherwise fallback to
  586. // using the original requested url.
  587. var serverUrl = xhr.getResponseHeader('X-PJAX-URL')
  588. obj.url = serverUrl ? stripInternalParams(parseURL(serverUrl)) : options.requestUrl
  589. // Attempt to parse response html into elements
  590. if (fullDocument) {
  591. var $head = $(parseHTML(data.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0]))
  592. var $body = $(parseHTML(data.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0]))
  593. } else {
  594. var $head = $body = $(parseHTML(data))
  595. }
  596. // If response data is empty, return fast
  597. if ($body.length === 0)
  598. return obj
  599. // If there's a <title> tag in the header, use it as
  600. // the page's title.
  601. obj.title = findAll($head, 'title').last().text()
  602. if (options.fragment) {
  603. // If they specified a fragment, look for it in the response
  604. // and pull it out.
  605. if (options.fragment === 'body') {
  606. var $fragment = $body
  607. } else {
  608. var $fragment = findAll($body, options.fragment).first()
  609. }
  610. if ($fragment.length) {
  611. obj.contents = options.fragment === 'body' ? $fragment : $fragment.contents()
  612. // If there's no title, look for data-title and title attributes
  613. // on the fragment
  614. if (!obj.title)
  615. obj.title = $fragment.attr('title') || $fragment.data('title')
  616. }
  617. } else if (!fullDocument) {
  618. obj.contents = $body
  619. }
  620. // Clean up any <title> tags
  621. if (obj.contents) {
  622. // Remove any parent title elements
  623. obj.contents = obj.contents.not(function () {
  624. return $(this).is('title')
  625. })
  626. // Then scrub any titles from their descendants
  627. obj.contents.find('title').remove()
  628. // Gather all script[src] elements
  629. obj.scripts = findAll(obj.contents, 'script[src]').remove()
  630. obj.contents = obj.contents.not(obj.scripts)
  631. }
  632. // Trim any whitespace off the title
  633. if (obj.title) obj.title = $.trim(obj.title)
  634. return obj
  635. }
  636. // Load an execute scripts using standard script request.
  637. //
  638. // Avoids jQuery's traditional $.getScript which does a XHR request and
  639. // globalEval.
  640. //
  641. // scripts - jQuery object of script Elements
  642. //
  643. // Returns nothing.
  644. function executeScriptTags(scripts) {
  645. if (!scripts) return
  646. var existingScripts = $('script[src]')
  647. scripts.each(function () {
  648. var src = this.src
  649. var matchedScripts = existingScripts.filter(function () {
  650. return this.src === src
  651. })
  652. if (matchedScripts.length) return
  653. var script = document.createElement('script')
  654. var type = $(this).attr('type')
  655. if (type) script.type = type
  656. script.src = $(this).attr('src')
  657. document.head.appendChild(script)
  658. })
  659. }
  660. // Internal: History DOM caching class.
  661. var cacheMapping = {}
  662. var cacheForwardStack = []
  663. var cacheBackStack = []
  664. // Push previous state id and container contents into the history
  665. // cache. Should be called in conjunction with `pushState` to save the
  666. // previous container contents.
  667. //
  668. // id - State ID Number
  669. // value - DOM Element to cache
  670. //
  671. // Returns nothing.
  672. function cachePush(id, value) {
  673. cacheMapping[id] = value
  674. cacheBackStack.push(id)
  675. // Remove all entries in forward history stack after pushing a new page.
  676. trimCacheStack(cacheForwardStack, 0)
  677. // Trim back history stack to max cache length.
  678. trimCacheStack(cacheBackStack, pjax.defaults.maxCacheLength)
  679. }
  680. // Shifts cache from directional history cache. Should be
  681. // called on `popstate` with the previous state id and container
  682. // contents.
  683. //
  684. // direction - "forward" or "back" String
  685. // id - State ID Number
  686. // value - DOM Element to cache
  687. //
  688. // Returns nothing.
  689. function cachePop(direction, id, value) {
  690. var pushStack, popStack
  691. cacheMapping[id] = value
  692. if (direction === 'forward') {
  693. pushStack = cacheBackStack
  694. popStack = cacheForwardStack
  695. } else {
  696. pushStack = cacheForwardStack
  697. popStack = cacheBackStack
  698. }
  699. pushStack.push(id)
  700. if (id = popStack.pop())
  701. delete cacheMapping[id]
  702. // Trim whichever stack we just pushed to to max cache length.
  703. trimCacheStack(pushStack, pjax.defaults.maxCacheLength)
  704. }
  705. // Trim a cache stack (either cacheBackStack or cacheForwardStack) to be no
  706. // longer than the specified length, deleting cached DOM elements as necessary.
  707. //
  708. // stack - Array of state IDs
  709. // length - Maximum length to trim to
  710. //
  711. // Returns nothing.
  712. function trimCacheStack(stack, length) {
  713. while (stack.length > length)
  714. delete cacheMapping[stack.shift()]
  715. }
  716. // Public: Find version identifier for the initial page load.
  717. //
  718. // Returns String version or undefined.
  719. function findVersion() {
  720. return $('meta').filter(function () {
  721. var name = $(this).attr('http-equiv')
  722. return name && name.toUpperCase() === 'X-PJAX-VERSION'
  723. }).attr('content')
  724. }
  725. // Install pjax functions on $.pjax to enable pushState behavior.
  726. //
  727. // Does nothing if already enabled.
  728. //
  729. // Examples
  730. //
  731. // $.pjax.enable()
  732. //
  733. // Returns nothing.
  734. function enable() {
  735. $.fn.pjax = fnPjax
  736. $.pjax = pjax
  737. $.pjax.enable = $.noop
  738. $.pjax.disable = disable
  739. $.pjax.click = handleClick
  740. $.pjax.submit = handleSubmit
  741. $.pjax.reload = pjaxReload
  742. $.pjax.defaults = {
  743. timeout: 650,
  744. push: true,
  745. replace: false,
  746. type: 'GET',
  747. dataType: 'html',
  748. scrollTo: 0,
  749. maxCacheLength: 20,
  750. version: findVersion
  751. }
  752. $(window).on('popstate.pjax', onPjaxPopstate)
  753. }
  754. // Disable pushState behavior.
  755. //
  756. // This is the case when a browser doesn't support pushState. It is
  757. // sometimes useful to disable pushState for debugging on a modern
  758. // browser.
  759. //
  760. // Examples
  761. //
  762. // $.pjax.disable()
  763. //
  764. // Returns nothing.
  765. function disable() {
  766. $.fn.pjax = function () {
  767. return this
  768. }
  769. $.pjax = fallbackPjax
  770. $.pjax.enable = enable
  771. $.pjax.disable = $.noop
  772. $.pjax.click = $.noop
  773. $.pjax.submit = $.noop
  774. $.pjax.reload = function () {
  775. window.location.reload()
  776. }
  777. $(window).off('popstate.pjax', onPjaxPopstate)
  778. }
  779. // Add the state property to jQuery's event object so we can use it in
  780. // $(window).bind('popstate')
  781. if ($.inArray('state', $.event.props) < 0)
  782. $.event.props.push('state')
  783. // Is pjax supported by this browser?
  784. $.support.pjax =
  785. window.history && window.history.pushState && window.history.replaceState &&
  786. // pushState isn't reliable on iOS until 5.
  787. !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/)
  788. $.support.pjax ? enable() : disable()
  789. })(jQuery);