Compare commits

...

15 Commits
0.2.4 ... dev

Author SHA1 Message Date
BehindTheMath
0916c74171 Merge pull request #93 from BehindTheMath/bugfix/add-switchElementsAlt
Add switchElementsAlt() to the default switches

Fixes #83.
2017-12-20 15:58:29 -05:00
Behind The Math
0781f820ee Add switchElementsAlt() to the default switches
Fixes #83.
2017-12-19 15:56:48 -05:00
Maxime Thirouin
a7b584c469 Add direct download link
Ref #57
2017-12-19 14:11:55 +01:00
Oskar
be5d58d550 Asynchronous switch functions (Make sure the DOM is parsed after switching) (#79)
* Make sure the DOM is parsed after switching

* Fix reload-link in the example
2017-12-19 13:58:22 +01:00
Bradley B Smith
1e40a0d70b Send the X-PJAX header with request (#80)
Make it more compatible with the jQuery PJAX and lets the server choose to optimize the response. Sending the list of selectors would be nice, too.
2017-12-19 13:56:30 +01:00
BehindTheMath
75eddfcab6 Add default switches to Pjax.switches (#92)
Fixes #68 and reverts #74
2017-12-19 13:49:26 +01:00
Maxime Thirouin
352e7114b6 Bye codesponsor 😢 2017-12-04 14:53:01 +01:00
markusfluer
af57adaafb Fixed #77 Fails on Internet Explorer 2017-11-02 13:02:17 +01:00
markusfluer
09f14fc86c Added evaluation of remote script tags 2017-11-02 12:51:36 +01:00
markusfluer
b17457f5a2 Fixed tests for request.js 2017-09-18 14:23:44 +02:00
markusfluer
86e5a2281a Added support do do a push-state ajax request with forms 2017-09-18 14:13:45 +02:00
Maxime Thirouin
109e78347f Update README.md 2017-09-14 21:45:39 +02:00
Markus Flür
cb3b6b8a5d Merge pull request #81 from CPTechnikVX/patch-1
Fix bug on IE11 preventing from ajax page refresh
2017-07-20 15:34:50 +02:00
CPTechnikVX
6dffeba21a Fix bug on IE11 preventing from ajax page refresh
It used to be fixed a long time ago, but was perhaps merged away...
2016-11-28 15:39:14 +01:00
Dale
acdd87ef3d README: Modified switches sidebySide example so it doesn't result in a undefined Type Error. (#74) 2016-09-27 07:07:28 +02:00
17 changed files with 279 additions and 51 deletions

View File

@@ -15,11 +15,26 @@ Especially for user that have low bandwidth connection._
**No more full page reload. No more lots of HTTP request.**
## Demo
[You can see this running on my website](http://moox.io), with sexy CSS animations when switching pages.
## Installation
You can install pjax from **npm**
```shell
$ npm install pjax
```
Pjax can obviously be downloaded directly.
[https://unpkg.com/pjax/pjax.js](https://unpkg.com/pjax/pjax.js)
## No dependencies
_There is nothing you need. No jQuery or something._
## How Pjax works
Pjax loads page using ajax & updates the browser's current url using pushState without reloading your page's layout or any resources (js, css), giving a fast page load.
@@ -98,26 +113,6 @@ _Magic! For real!_ **There is completely no need to do anything on server side!*
- Allow page transition with CSS animations,
- Can be easily hacked since every method is public (so overridable)
## Installation
You can install pjax from **npm**
```shell
$ npm install pjax
```
Or using **bower**
```shell
$ bower install pjax
```
Pjax can obviously be downloaded directly.
## No dependencies
_There is nothing you need. No jQuery or something._
## Compatibility
Pjax only works with [browsers that support the `history.pushState` API](http://caniuse.com/#search=pushstate).

View File

@@ -19,7 +19,8 @@ document.addEventListener("pjax:success", function() {
document.addEventListener("DOMContentLoaded", function() {
var pjax = new Pjax({
selectors: [".body"],
elements: [".js-Pjax"],
selectors: [".body"]
// currentUrlFullReload: true,
})
console.log("Pjax initialized.", pjax)

View File

@@ -10,7 +10,7 @@
<div class='body'>
<h1>Index</h1>
Hello.
Go to <a href='page2.html'>Page 2</a> and view your console to see Pjax events.
Go to <a href='page2.html' class="js-Pjax">Page 2</a> and view your console to see Pjax events.
Clicking on <a href='index.html'>this page</a> will just reload the page entierly.
</div>
</body>

View File

@@ -9,7 +9,7 @@
<body>
<div class='body'>
<h1>Page 2</h1>
Hello. Go to <a href='index.html'>Index</a>.
Hello. Go to <a href='index.html' class="js-Pjax">Index</a>.
</div>
</body>
</html>

View File

@@ -9,6 +9,8 @@ var on = require("./lib/events/on.js")
// var off = require("./lib/events/on.js")
var trigger = require("./lib/events/trigger.js")
var defaultSwitches = require("./lib/switches")
var Pjax = function(options) {
this.firstrun = true
@@ -27,7 +29,7 @@ var Pjax = function(options) {
opt.url = st.state.url
opt.title = st.state.title
opt.history = false
opt.requestOptions = {};
if (st.state.uid < this.lastUid) {
opt.backward = true
}
@@ -42,6 +44,8 @@ var Pjax = function(options) {
}.bind(this))
}
Pjax.switches = defaultSwitches
Pjax.prototype = {
log: require("./lib/proto/log.js"),
@@ -55,6 +59,8 @@ Pjax.prototype = {
attachLink: require("./lib/proto/attach-link.js"),
attachForm: require("./lib/proto/attach-form.js"),
forEachSelectors: function(cb, context, DOMcontext) {
return require("./lib/foreach-selectors.js").bind(this)(this.options.selectors, cb, context, DOMcontext)
},
@@ -77,11 +83,12 @@ Pjax.prototype = {
},
onSwitch: function() {
this.parseDOM(document)
trigger(window, "resize scroll")
},
loadContent: function(html, options) {
var tmpEl = document.implementation.createHTMLDocument()
var tmpEl = document.implementation.createHTMLDocument("pjax")
// parse HTML attributes to copy them
// since we are forced to use documentElement.innerHTML (outerHTML can't be used for <html>)
@@ -151,7 +158,7 @@ Pjax.prototype = {
trigger(document, "pjax:send", options);
// Do the request
this.doRequest(href, function(html) {
this.doRequest(href, options.requestOptions, function(html) {
// Fail if unable to load HTML via AJAX
if (html === false) {
trigger(document,"pjax:complete pjax:error", options)

View File

@@ -2,7 +2,8 @@ module.exports = function(el) {
// console.log("going to execute script", el)
var code = (el.text || el.textContent || el.innerHTML || "")
var head = document.querySelector("head") || document.documentElement
var src = (el.src || "");
var parent = el.parentNode || document.querySelector("head") || document.documentElement
var script = document.createElement("script")
if (code.match("document.write")) {
@@ -13,6 +14,14 @@ module.exports = function(el) {
}
script.type = "text/javascript"
if (src != "") {
script.src = src;
script.onload = function() { document.dispatchEvent((new Event("pjax:complete"))); }
script.async = false; // force asynchronous loading of peripheral js
}
if (code != "") {
try {
script.appendChild(document.createTextNode(code))
}
@@ -20,10 +29,14 @@ module.exports = function(el) {
// old IEs have funky script nodes
script.text = code
}
}
// execute
head.insertBefore(script, head.firstChild)
head.removeChild(script) // avoid pollution
parent.appendChild(script);
// avoid pollution only in head or body tags
if (["head","body"].indexOf(parent.tagName.toLowerCase()) > 0) {
parent.removeChild(script)
}
return true
return true;
}

View File

@@ -4,12 +4,17 @@ var evalScript = require("./eval-script")
// Needed since innerHTML does not run scripts
module.exports = function(el) {
// console.log("going to execute scripts for ", el)
if (el.tagName.toLowerCase() === "script") {
evalScript(el);
}
forEachEls(el.querySelectorAll("script"), function(script) {
if (!script.type || script.type.toLowerCase() === "text/javascript") {
if (script.parentNode) {
script.parentNode.removeChild(script)
}
evalScript(script)
evalScript(script);
}
})
});
}

93
lib/proto/attach-form.js Normal file
View File

@@ -0,0 +1,93 @@
require("../polyfills/Function.prototype.bind")
var on = require("../events/on")
var clone = require("../clone")
var attrClick = "data-pjax-click-state"
var formAction = function(el, event){
this.options.requestOptions = {
requestUrl : el.getAttribute('action') || window.location.href,
requestMethod : el.getAttribute('method') || 'GET',
}
//create a testable virtual link of the form action
var virtLinkElement = document.createElement('a');
virtLinkElement.setAttribute('href', this.options.requestOptions.requestUrl);
// Ignore external links.
if (virtLinkElement.protocol !== window.location.protocol || virtLinkElement.host !== window.location.host) {
el.setAttribute(attrClick, "external");
return
}
// Ignore click if we are on an anchor on the same page
if (virtLinkElement.pathname === window.location.pathname && virtLinkElement.hash.length > 0) {
el.setAttribute(attrClick, "anchor-present");
return
}
// Ignore empty anchor "foo.html#"
if (virtLinkElement.href === window.location.href.split("#")[0] + "#") {
el.setAttribute(attrClick, "anchor-empty")
return
}
// if declared as a full reload, just normally submit the form
if ( this.options.currentUrlFullReload) {
el.setAttribute(attrClick, "reload");
return;
}
event.preventDefault()
var paramObject = [];
for(var elementKey in el.elements) {
var element = el.elements[elementKey];
if (!!element.name && element.attributes !== undefined && element.tagName.toLowerCase() !== 'button'){
if ((element.attributes.type !== 'checkbox' && element.attributes.type !== 'radio') || element.checked) {
paramObject.push({ name: encodeURIComponent(element.name), value: encodeURIComponent(element.value)});
}
}
}
//Creating a getString
var paramsString = (paramObject.map(function(value){return value.name+"="+value.value;})).join('&');
this.options.requestOptions.requestPayload = paramObject;
this.options.requestOptions.requestPayloadString = paramsString;
el.setAttribute(attrClick, "submit");
this.loadUrl(virtLinkElement.href, clone(this.options))
};
var isDefaultPrevented = function(event) {
return event.defaultPrevented || event.returnValue === false;
};
module.exports = function(el) {
var that = this
on(el, "submit", function(event) {
if (isDefaultPrevented(event)) {
return
}
formAction.call(that, el, event)
})
on(el, "keyup", function(event) {
if (isDefaultPrevented(event)) {
return
}
if (event.keyCode == 13) {
formAction.call(that, el, event)
}
}.bind(this))
}

View File

@@ -51,7 +51,7 @@ var linkAction = function(el, event) {
this.reload()
return
}
this.options.requestOptions = this.options.requestOptions || {};
el.setAttribute(attrClick, "load")
this.loadUrl(el.href, clone(this.options))
}

View File

@@ -8,7 +8,10 @@ module.exports = function(el) {
break
case "form":
throw "Pjax doesnt support <form> yet."
// only attach link if el does not already have link attached
if (!el.hasAttribute('data-pjax-click-state')) {
this.attachForm(el)
}
break
default:

View File

@@ -1,5 +1,7 @@
/* global _gaq: true, ga: true */
var defaultSwitches = require("../switches")
module.exports = function(options){
this.options = options
this.options.elements = this.options.elements || "a[href], form[action]"
@@ -27,10 +29,10 @@ module.exports = function(options){
// if you set head.outerHTML, a new body tag is appended, so the dom get 2 body
// & it break the switchFallback which replace head & body
if (!this.options.switches.head) {
this.options.switches.head = this.switchElementsAlt
this.options.switches.head = defaultSwitches.switchElementsAlt
}
if (!this.options.switches.body) {
this.options.switches.body = this.switchElementsAlt
this.options.switches.body = defaultSwitches.switchElementsAlt
}
if (typeof options.analytics !== "function") {
options.analytics = function() {}

View File

@@ -1,4 +1,7 @@
module.exports = function(location, callback) {
module.exports = function(location, options, callback) {
options = options || {};
var requestMethod = options.requestMethod || "GET";
var requestPayload = options.requestPayloadString || null;
var request = new XMLHttpRequest()
request.onreadystatechange = function() {
@@ -17,8 +20,17 @@ module.exports = function(location, callback) {
location += (!/[?&]/.test(location) ? "?" : "&") + new Date().getTime()
}
request.open("GET", location, true)
request.open(requestMethod.toUpperCase(), location, true)
request.setRequestHeader("X-Requested-With", "XMLHttpRequest")
request.send(null)
request.setRequestHeader("X-PJAX", "true")
// Add the request payload if available
if (options.requestPayloadString != undefined && options.requestPayloadString != "") {
// Send the proper header information along with the request
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
request.send(requestPayload)
return request
}

View File

@@ -15,6 +15,20 @@ module.exports = {
this.onSwitch()
},
switchElementsAlt: function(oldEl, newEl) {
oldEl.innerHTML = newEl.innerHTML
// Copy attributes from the new element to the old one
if (newEl.hasAttributes()) {
const attrs = newEl.attributes;
for (var i = 0; i < attrs.length; i++) {
oldEl.attributes.setNamedItem(attrs[i])
}
}
this.onSwitch()
},
sideBySide: function(oldEl, newEl, options, switchOptions) {
var forEach = Array.prototype.forEach
var elsToRemove = []

View File

@@ -34,6 +34,7 @@
"scripts": {
"lint": "jscs **/*.js && jshint . --exclude-path .gitignore",
"standalone": "browserify index.js --standalone Pjax > pjax.js",
"build-debug": "browserify index.js --debug --standalone Pjax > pjax.js",
"tests": "testling",
"test": "npm run lint && npm run standalone && npm run tests",
"test--html": "testling --html > tests/scripts/index.html",

View File

@@ -0,0 +1,78 @@
var tape = require("tape")
var on = require("../../../lib/events/on")
var trigger = require("../../../lib/events/trigger")
var attachForm = require("../../../lib/proto/attach-form")
var form = document.createElement("form")
var attr = "data-pjax-click-state"
var preventDefault = function(e) { e.preventDefault() }
tape("test attach form prototype method", function(t) {
t.plan(7)
attachForm.call({
options: {},
reload: function() {
t.equal(form.getAttribute(attr), "reload", "triggering a simple reload will just submit the form")
},
loadUrl: function() {
t.equal(form.getAttribute(attr), "submit", "triggering a post to the next page")
}
}, form)
var internalUri = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
form.action = "http://external.com/"
trigger(form, "submit")
t.equal(form.getAttribute(attr), "external", "external url stop behavior")
form.action = internalUri + "#anchor"
trigger(form, "submit")
t.equal(form.getAttribute(attr), "anchor-present", "internal anchor stop behavior")
window.location.hash = "#anchor"
form.action = internalUri + "#another-anchor"
trigger(form, "submit")
t.notEqual(form.getAttribute(attr), "anchor", "differents anchors stop behavior")
window.location.hash = ""
form.action = internalUri + "#"
trigger(form, "submit")
t.equal(form.getAttribute(attr), "anchor-empty", "empty anchor stop behavior")
form.action = internalUri
trigger(form, "submit")
// see reload defined above
form.action = window.location.protocol + "//" + window.location.host + "/internal"
form.method = 'POST'
trigger(form, "submit")
// see post defined above
form.action = window.location.protocol + "//" + window.location.host + "/internal"
form.method = 'GET'
trigger(form, "submit")
// see post defined above
t.end()
})
tape("test attach form preventDefaulted events", function(t) {
var callbacked = false
var form = document.createElement("form")
attachForm.call({
options: {},
loadUrl: function() {
callbacked = true
}
}, form)
form.action = "#"
on(form, "submit", preventDefault)
trigger(form, "submit")
t.equal(callbacked, false, "events that are preventDefaulted should not fire callback")
t.end()
})

View File

@@ -1,17 +1,21 @@
var tape = require("tape")
var parseElement = require("../../../lib/proto/parse-element")
var protoMock = {attachLink: function() { return true}}
var protoMock = {
attachLink: function() { return true },
attachForm: function() { return true }
}
tape("test parse element prototype method", function(t) {
t.doesNotThrow(function() {
var a = document.createElement("a")
parseElement.call(protoMock, a)
}, "<a> element can be parsed")
t.throws(function() {
t.doesNotThrow(function() {
var form = document.createElement("form")
parseElement.call(protoMock, form)
}, "<form> cannot be used (for now)")
}, "<form> element can be parsed")
t.end()
})

View File

@@ -21,7 +21,7 @@ tape("test xhr request", function(t) {
cacheBust: true,
},
});
var r = requestCacheBust("https://api.github.com/", function(result) {
var r = requestCacheBust("https://api.github.com/", {}, function(result) {
t.equal(r.responseURL.indexOf("?"), 23, "XHR URL is cache-busted when configured to be")
try {
result = JSON.parse(result)
@@ -39,7 +39,7 @@ tape("test xhr request", function(t) {
cacheBust: false,
},
});
var r = requestNoCacheBust("https://api.github.com/", function() {
var r = requestNoCacheBust("https://api.github.com/", {}, function() {
t.equal(r.responseURL, "https://api.github.com/", "XHR URL is left untouched")
t.end()
})