Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. # pjax
  2. .--.
  3. / \
  4. ## a a
  5. ( '._)
  6. |'-- |
  7. _.\___/_ ___pjax___
  8. ."\> \Y/|<'. '._.-'
  9. / \ \_\/ / '-' /
  10. | --'\_/|/ | _/
  11. |___.-' | |`'`
  12. | | |
  13. | / './
  14. /__./` | |
  15. \ | |
  16. \ | |
  17. ; | |
  18. / | |
  19. jgs |___\_.\_
  20. `-"--'---'
  21. ## pjax = pushState + ajax
  22. pjax is a jQuery plugin that uses ajax and pushState to deliver a fast browsing experience with real permalinks, page titles, and a working back button.
  23. pjax works by grabbing html from your server via ajax and replacing the content of a container on your page with the ajax'd html. It then updates the browser's current url using pushState without reloading your page's layout or any resources (js, css), giving the appearance of a fast, full page load. But really it's just ajax and pushState.
  24. For [browsers that don't support pushState][compat] pjax fully degrades.
  25. ## Overview
  26. pjax is not fully automatic. You'll need to setup and designate a containing element on your page that will be replaced when you navigate your site.
  27. Consider the following page.
  28. ``` html
  29. <!DOCTYPE html>
  30. <html>
  31. <head>
  32. <!-- styles, scripts, etc -->
  33. </head>
  34. <body>
  35. <h1>My Site</h1>
  36. <div class="container" id="pjax-container">
  37. Go to <a href="/page/2">next page</a>.
  38. </div>
  39. </body>
  40. </html>
  41. ```
  42. We want pjax to grab the url `/page/2` then replace `#pjax-container` with whatever it gets back. No styles or scripts will be reloaded and even the h1 can stay the same - we just want to change the `#pjax-container` element.
  43. We do this by telling pjax to listen on `a` tags and use `#pjax-container` as the target container:
  44. ``` javascript
  45. $(document).pjax('a', '#pjax-container')
  46. ```
  47. Now when someone in a pjax-compatible browser clicks "next page" the content of `#pjax-container` will be replaced with the body of `/page/2`.
  48. Magic! Almost. You still need to configure your server to look for pjax requests and send back pjax-specific content.
  49. The pjax ajax request sends an `X-PJAX` header so in this example (and in most cases) we want to return just the content of the page without any layout for any requests with that header.
  50. Here's what it might look like in Rails:
  51. ``` ruby
  52. def index
  53. if request.headers['X-PJAX']
  54. render :layout => false
  55. end
  56. end
  57. ```
  58. If you'd like a more automatic solution than pjax for Rails check out [Turbolinks](https://github.com/rails/turbolinks).
  59. Also check out [RailsCasts #294 : Playing with PJAX](http://railscasts.com/episodes/294-playing-with-pjax)
  60. ## Installation
  61. ### bower
  62. Via [bower](https://github.com/twitter/bower).
  63. ```
  64. $ bower install jquery-pjax
  65. ```
  66. Or add `jquery-pjax` to your apps `bower.json`.
  67. ``` json
  68. "dependencies": {
  69. "jquery-pjax": "latest"
  70. }
  71. ```
  72. ### standalone
  73. pjax can be downloaded directly into your app's public directory - just be sure you've loaded jQuery first.
  74. ```
  75. curl -LO https://raw.github.com/defunkt/jquery-pjax/master/jquery.pjax.js
  76. ```
  77. **WARNING** Do not hotlink the raw script url. GitHub is not a CDN.
  78. ## Dependencies
  79. Requires jQuery 1.8.x or higher.
  80. ## Compatibility
  81. pjax only works with [browsers that support the `history.pushState` API][compat]. When the API isn't supported pjax goes into fallback mode: `$.fn.pjax` calls will be a no-op and `$.pjax` will hard load the given url. This mode targets the browser requirements of the jQuery version being used.
  82. For debugging purposes, you can intentionally disable pjax even if the browser supports `pushState`. Just call `$.pjax.disable()`. To see if pjax is actually supports `pushState`, check `$.support.pjax`.
  83. ## Usage
  84. ### `$.fn.pjax`
  85. Let's talk more about the most basic way to get started:
  86. ``` javascript
  87. $(document).pjax('a', '#pjax-container')
  88. ```
  89. This will enable pjax on all links and designate the container as `#pjax-container`.
  90. If you are migrating an existing site you probably don't want to enable pjax everywhere just yet. Instead of using a global selector like `a` try annotating pjaxable links with `data-pjax`, then use `'a[data-pjax]'` as your selector.
  91. Or try this selector that matches any `<a data-pjax href=>` links inside a `<div data-pjax>` container.
  92. ``` javascript
  93. $(document).pjax('[data-pjax] a, a[data-pjax]', '#pjax-container')
  94. ```
  95. #### Arguments
  96. The synopsis for the `$.fn.pjax` function is:
  97. ``` javascript
  98. $(document).pjax(selector, [container], options)
  99. ```
  100. 1. `selector` is a string to be used for click [event delegation][$.fn.on].
  101. 2. `container` is a string selector that uniquely identifies the pjax container.
  102. 3. `options` is an object with keys described below.
  103. ##### pjax options
  104. key | default | description
  105. ----|---------|------------
  106. `timeout` | 650 | ajax timeout in milliseconds after which a full refresh is forced
  107. `push` | true | use [pushState][] to add a browser history entry upon navigation
  108. `replace` | false | replace URL without adding browser history entry
  109. `maxCacheLength` | 20 | maximum cache size for previous container contents
  110. `version` | | a string or function returning the current pjax version
  111. `scrollTo` | 0 | vertical position to scroll to after navigation
  112. `type` | `"GET"` | see [$.ajax][]
  113. `dataType` | `"html"` | see [$.ajax][]
  114. `container` | | CSS selector for the element where content should be replaced
  115. `url` | link.href | a string or function that returns the URL for the ajax request
  116. `target` | link | eventually the `relatedTarget` value for [pjax events](#events)
  117. `fragment` | `"body"` | CSS selector for the fragment to extract from ajax response
  118. You can change the defaults globally by writing to the `$.pjax.defaults` object:
  119. ``` javascript
  120. $.pjax.defaults.timeout = 1200
  121. ```
  122. ### `$.pjax.click`
  123. This is a lower level function used by `$.fn.pjax` itself. It allows you to get a little more control over the pjax event handling.
  124. This example uses the current click context to set an ancestor as the container:
  125. ``` javascript
  126. if ($.support.pjax) {
  127. $(document).on('click', 'a[data-pjax]', function(event) {
  128. var container = $(this).closest('[data-pjax-container]')
  129. $.pjax.click(event, {container: container})
  130. })
  131. }
  132. ```
  133. **NOTE** Use the explicit `$.support.pjax` guard. We aren't using `$.fn.pjax` so we should avoid binding this event handler unless the browser is actually going to use pjax.
  134. ### `$.pjax.submit`
  135. Submits a form via pjax. This function is experimental but GitHub uses it on [Gist][gist] so give it a shot!
  136. ``` javascript
  137. $(document).on('submit', 'form[data-pjax]', function(event) {
  138. $.pjax.submit(event, '#pjax-container')
  139. })
  140. ```
  141. ### `$.pjax.reload`
  142. Initiates a request for the current URL to the server using pjax mechanism and replaces the container with the response. Does not add a browser history entry.
  143. ``` javascript
  144. $.pjax.reload('#pjax-container', options)
  145. ```
  146. ### `$.pjax`
  147. Manual pjax invocation. Used mainly when you want to start a pjax request in a handler that didn't originate from a click. If you can get access to a click `event`, consider `$.pjax.click(event)` instead.
  148. ``` javascript
  149. function applyFilters() {
  150. var url = urlForFilters()
  151. $.pjax({url: url, container: '#pjax-container'})
  152. }
  153. ```
  154. ### Events
  155. All pjax events except `pjax:click` & `pjax:clicked` are fired from the pjax
  156. container, not the link that was clicked.
  157. <table>
  158. <tr>
  159. <th>event</th>
  160. <th>cancel</th>
  161. <th>arguments</th>
  162. <th>notes</th>
  163. </tr>
  164. <tr>
  165. <th colspan=4>event lifecycle upon following a pjaxed link</th>
  166. </tr>
  167. <tr>
  168. <td><code>pjax:click</code></td>
  169. <td>✔︎</td>
  170. <td><code>options</code></td>
  171. <td>fires from a link that got activated; cancel to prevent pjax</td>
  172. </tr>
  173. <tr>
  174. <td><code>pjax:beforeSend</code></td>
  175. <td>✔︎</td>
  176. <td><code>xhr, options</code></td>
  177. <td>can set XHR headers</td>
  178. </tr>
  179. <tr>
  180. <td><code>pjax:start</code></td>
  181. <td></td>
  182. <td><code>xhr, options</code></td>
  183. <td></td>
  184. </tr>
  185. <tr>
  186. <td><code>pjax:send</code></td>
  187. <td></td>
  188. <td><code>xhr, options</code></td>
  189. <td></td>
  190. </tr>
  191. <tr>
  192. <td><code>pjax:clicked</code></td>
  193. <td></td>
  194. <td><code>options</code></td>
  195. <td>fires after pjax has started from a link that got clicked</td>
  196. </tr>
  197. <tr>
  198. <td><code>pjax:beforeReplace</code></td>
  199. <td></td>
  200. <td><code>contents, options</code></td>
  201. <td>before replacing HTML with content loaded from the server</td>
  202. </tr>
  203. <tr>
  204. <td><code>pjax:success</code></td>
  205. <td></td>
  206. <td><code>data, status, xhr, options</code></td>
  207. <td>after replacing HTML content loaded from the server</td>
  208. </tr>
  209. <tr>
  210. <td><code>pjax:timeout</code></td>
  211. <td>✔︎</td>
  212. <td><code>xhr, options</code></td>
  213. <td>fires after <code>options.timeout</code>; will hard refresh unless canceled</td>
  214. </tr>
  215. <tr>
  216. <td><code>pjax:error</code></td>
  217. <td>✔︎</td>
  218. <td><code>xhr, textStatus, error, options</code></td>
  219. <td>on ajax error; will hard refresh unless canceled</td>
  220. </tr>
  221. <tr>
  222. <td><code>pjax:complete</code></td>
  223. <td></td>
  224. <td><code>xhr, textStatus, options</code></td>
  225. <td>always fires after ajax, regardless of result</td>
  226. </tr>
  227. <tr>
  228. <td><code>pjax:end</code></td>
  229. <td></td>
  230. <td><code>xhr, options</code></td>
  231. <td></td>
  232. </tr>
  233. <tr>
  234. <th colspan=4>event lifecycle on browser Back/Forward navigation</th>
  235. </tr>
  236. <tr>
  237. <td><code>pjax:popstate</code></td>
  238. <td></td>
  239. <td></td>
  240. <td>event <code>direction</code> property: &quot;back&quot;/&quot;forward&quot;</td>
  241. </tr>
  242. <tr>
  243. <td><code>pjax:start</code></td>
  244. <td></td>
  245. <td><code>null, options</code></td>
  246. <td>before replacing content</td>
  247. </tr>
  248. <tr>
  249. <td><code>pjax:beforeReplace</code></td>
  250. <td></td>
  251. <td><code>contents, options</code></td>
  252. <td>right before replacing HTML with content from cache</td>
  253. </tr>
  254. <tr>
  255. <td><code>pjax:end</code></td>
  256. <td></td>
  257. <td><code>null, options</code></td>
  258. <td>after replacing content</td>
  259. </tr>
  260. </table>
  261. `pjax:send` & `pjax:complete` are a good pair of events to use if you are implementing a
  262. loading indicator. They'll only be triggered if an actual XHR request is made,
  263. not if the content is loaded from cache:
  264. ``` javascript
  265. $(document).on('pjax:send', function() {
  266. $('#loading').show()
  267. })
  268. $(document).on('pjax:complete', function() {
  269. $('#loading').hide()
  270. })
  271. ```
  272. An example of canceling a `pjax:timeout` event would be to disable the fallback
  273. timeout behavior if a spinner is being shown:
  274. ``` javascript
  275. $(document).on('pjax:timeout', function(event) {
  276. // Prevent default timeout redirection behavior
  277. event.preventDefault()
  278. })
  279. ```
  280. ### Server side
  281. Server configuration will vary between languages and frameworks. The following example shows how you might configure Rails.
  282. ``` ruby
  283. def index
  284. if request.headers['X-PJAX']
  285. render :layout => false
  286. end
  287. end
  288. ```
  289. An `X-PJAX` request header is set to differentiate a pjax request from normal XHR requests. In this case, if the request is pjax, we skip the layout html and just render the inner contents of the container.
  290. Check if your favorite server framework supports pjax here: https://gist.github.com/4283721
  291. #### Layout Reloading
  292. Layouts can be forced to do a hard reload when assets or html changes.
  293. First set the initial layout version in your header with a custom meta tag.
  294. ``` html
  295. <meta http-equiv="x-pjax-version" content="v123">
  296. ```
  297. Then from the server side, set the `X-PJAX-Version` header to the same.
  298. ``` ruby
  299. if request.headers['X-PJAX']
  300. response.headers['X-PJAX-Version'] = "v123"
  301. end
  302. ```
  303. Deploying a deploy, bumping the version constant to force clients to do a full reload the next request getting the new layout and assets.
  304. ### Legacy API
  305. Pre 1.0 versions used an older style syntax that was analogous to the now deprecated `$.fn.live` api. The current api is based off `$.fn.on`.
  306. ``` javascript
  307. $('a[data-pjax]').pjax('#pjax-container')
  308. ```
  309. Expanded to
  310. ``` javascript
  311. $('a[data-pjax]').live('click', function(event) {
  312. $.pjax.click(event, '#pjax-container')
  313. })
  314. ```
  315. The new api
  316. ``` javascript
  317. $(document).pjax('a[data-pjax]', '#pjax-container')
  318. ```
  319. Which is roughly the same as
  320. ``` javascript
  321. $(document).on('click', 'a[data-pjax]', function(event) {
  322. $.pjax.click(event, '#pjax-container')
  323. })
  324. ```
  325. **NOTE** The new api gives you control over the delegated element container. `$.fn.live` always bound to `document`. This is what you still want to do most of the time.
  326. ## Contributing
  327. ```
  328. $ git clone https://github.com/defunkt/jquery-pjax.git
  329. $ cd jquery-pjax/
  330. ```
  331. To run the test suite locally, start up the Sinatra test application.
  332. ```
  333. $ bundle install
  334. $ bundle exec ruby test/app.rb
  335. == Sinatra/1.4.5 has taken the stage on 4567 for development with backup from WEBrick
  336. # in another tab:
  337. $ open http://localhost:4567/
  338. ```
  339. [compat]: http://caniuse.com/#search=pushstate
  340. [gist]: https://gist.github.com/
  341. [$.fn.on]: http://api.jquery.com/on/
  342. [$.ajax]: http://api.jquery.com/jQuery.ajax/
  343. [pushState]: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries