-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathjquery.fs.pronto.js
494 lines (428 loc) · 12.2 KB
/
jquery.fs.pronto.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
* Pronto v3.2.1 - 2015-04-04
* A jQuery plugin for faster page loads. Part of the formstone library.
* http://classic.formstone.it/pronto/
*
* Copyright 2015 Ben Plum; MIT Licensed
*/
;(function ($, window) {
"use strict";
/* global ga */
var $window = $(window),
$body,
navtiveSupport = window.history && window.history.pushState && window.history.replaceState,
currentURL = '',
visited = 0,
request = null;
/**
* @options
* @param cache [boolean] <true> "Cache AJAX responses"
* @param force [boolean] <false> "Forces new requests when navigating back/forward"
* @param jump [boolean] <false> "Jump page to top on render"
* @param modal [boolean] <false> "Flag for content loaded into modal"
* @param selecter [string] <'a'> "Selecter to target in the DOM"
* @param render [function] <$.noop> "Custom render function"
* @param requestKey [string] <'pronto'> "GET variable for requests"
* @param target [object] <{ title: 'title', content: '#pronto' }> "Key / value pair for rendering responses (key is response key, value is target selector)"
* @param tracking.legacy [boolean] <false> "Flag for legacy Google Analytics tracking"
* @param tracking.manager [boolean] <false> "Flag for Tag Manager tracking"
* @param tracking.variable [string] <'currentURL'> "Tag Manager dataLayer variable name (macro in Tag Manager)"
* @param tracking.event [string] <'PageView'> "Tag Manager event name (rule in Tag Manager)"
* @param transitionOut [function] <$.noop> "Transition timing callback; should return user defined $.Deferred object, which must eventually resolve"
*/
var options = {
cache: true,
force: false,
jump: true,
modal: false,
selector: "a",
render: $.noop,
requestKey: "pronto",
target: {
title: "title",
content: "#pronto"
},
tracking: {
legacy: false, // Use legacy ga code
manager: false, // Use tag manager events
variable: 'currentURL', // data layer variable name - macro in tag manager
event: 'PageView' // event name - rule in tag manager
},
transitionOut: $.noop
};
/**
* @events
* @event pronto.request "Before request is made; triggered on window. Second parameter 'true' if pop event"
* @event pronto.progress "As request is loaded; triggered on window"
* @event pronto.load "After request is loaded; triggered on window"
* @event pronto.render "After state is rendered; triggered on window"
* @event pronto.error "After load error; triggered on window"
*/
var pub = {
/**
* @method
* @name defaults
* @description Sets default plugin options
* @param opts [object] <{}> "Options object"
* @example $.pronto("defaults", opts);
*/
defaults: function(opts) {
options = $.extend(options, opts || {});
return (typeof this === 'object') ? $(this) : true;
},
/**
* @method
* @name disable
* @description Disable Pronto
* @example $.pronto("enable");
*/
disable: function() {
if ($body && $body.hasClass("pronto")) {
$body.off("click.pronto")
.removeClass("pronto");
}
},
/**
* @method
* @name enable
* @description Enables Pronto
* @example $.pronto("enable");
*/
enable: function() {
if ($body && !$body.hasClass("pronto")) {
$body.on("click.pronto", options.selector, _onClick)
.addClass("pronto");
}
},
/**
* @method
* @name load
* @description Loads new page
* @param opts [url] <''> "URL to load"
* @example $.pronto("load", "http://website.com/page/");
*/
load: function(url) {
if (!navtiveSupport) {
window.location.href = url;
} else if (url) {
_request(url);
}
return;
}
};
/**
* @method private
* @name _init
* @description Initializes plugin
* @param opts [object] "Initialization options"
*/
function _init(opts) {
// Check for push/pop support
if (!navtiveSupport) {
return;
}
$body = $("body");
if (!$body.hasClass("pronto")) {
$.extend(true, options, opts || {});
options.$container = $(options.container);
if (options.render === $.noop) {
options.render = _renderState;
}
if (options.transitionOut === $.noop) {
options.transitionOut = function() {
return $.Deferred().resolve();
};
}
// Capture current url & state
currentURL = window.location.href;
// Set initial state
_saveState();
// Bind state events
$window.on("popstate.pronto", _onPop);
pub.enable();
}
}
/**
* @method private
* @name _onClick
* @description Handles click events
* @param e [object] "Event data"
*/
function _onClick(e) {
var url = e.currentTarget;
// Ignore everything but normal click
if ( (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) || (window.location.protocol !== url.protocol || window.location.host !== url.host) || url.target === "_blank" ) {
return;
}
// Update state on hash change
if (url.hash && (url.href.replace(url.hash, '') === window.location.href.replace(location.hash, '') || url.href === window.location.href + '#')) {
_saveState();
return;
}
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
if (currentURL === url.href) {
_saveState();
} else {
_request(url.href);
}
}
/**
* @method private
* @name _onPop
* @description Handles history navigation events
* @param e [object] "Event data"
*/
function _onPop(e) {
var data = e.originalEvent.state;
if (data) {
if (options.modal && visited === 0 && data.url && !data.initial) {
// If opening content in a 'modal', return to original page on reload->back
window.location.href = data.url;
} else {
// Check if data exists
if (data.url !== currentURL) {
if (options.force) {
// Force a new request, even if navigating back
_request(data.url);
} else {
// Fire request event
$window.trigger("pronto.request", [ true ]);
_process(data.url, data.hash, data.data, data.scroll, false);
}
}
}
}
}
/**
* @method private
* @name _request
* @description Requests new content via AJAX
* @param url [string] "URL to load"
*/
function _request(url) {
// Fire request event
$window.trigger("pronto.request", [ false ]);
// Get transition out deferred
options.transitionOutDeferred = options.transitionOut.apply(window, [ false ]);
var queryIndex = url.indexOf("?"),
hashIndex = url.indexOf("#"),
data = (queryIndex > -1) ? _getQueryParams( url.slice( queryIndex + 1 ) ) : {},
hash = "",
requestDeferred = $.Deferred(),
error = "User error",
response = null;
if (hashIndex > -1) {
hash = (queryIndex > -1) ? url.slice(hashIndex, queryIndex) : url.slice(hashIndex);
}
data[ options.requestKey ] = true;
// Request new content
request = $.ajax({
url: url,
data: data,
dataType: "json",
cache: options.cache,
xhr: function() {
// custom xhr
var xhr = new window.XMLHttpRequest();
/*
//Upload progress ?
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percent = (e.loaded / e.total) / 2;
$window.trigger("pronto.progress", [ percent ]);
}
}, false);
*/
//Download progress
xhr.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percent = e.loaded / e.total;
$window.trigger("pronto.progress", [ percent ]);
}
}, false);
return xhr;
},
success: function(resp, status, jqXHR) {
response = (typeof resp === "string") ? $.parseJSON(resp) : resp;
// handle redirects - requires passing new location with json response
if (resp.location) {
url = resp.location;
}
requestDeferred.resolve();
},
error: function(jqXHR, status, err) {
error = err;
requestDeferred.reject();
// Try to parse response text
try {
// response = $.parseJSON(jqXHR.responseText);
// _process(url, hash, response, 0, true);
} catch (e) {
// console.error(e);
}
}
});
$.when(requestDeferred, options.transitionOutDeferred).done(function() {
_process(url, hash, response, (options.jump ? 0 : false), true);
}).fail(function() {
$window.trigger("pronto.error", [ error ]);
});
}
/**
* @method private
* @name _process
* @description Processes a state
* @param url [string] "State URL"
* @param data [object] "State Data"
* @param scrollTop [int] "Current scroll position"
* @param doPush [boolean] "Flag to replace or add state"
*/
function _process(url, hash, data, scrollTop, doPush) {
// Fire load event
$window.trigger("pronto.load");
// Trigger analytics page view
_track(url);
// Update current state before rendering new state
_saveState();
// Render before updating
options.render.call(this, data, hash);
// Update current url
currentURL = url;
if (doPush) {
// Push new states to the stack
history.pushState({
url: currentURL,
data: data,
scroll: scrollTop,
hash: hash
}, "state-"+currentURL, currentURL);
visited++;
} else {
// Update state with history data
_saveState();
}
$window.trigger("pronto.render");
if (hash !== "") {
var $el = $(hash);
if ($el.length) {
scrollTop = $el.offset().top;
}
}
if (scrollTop !== false) {
$window.scrollTop(scrollTop);
}
}
/**
* @method private
* @name _renderState
* @description Renders a new state
* @param data [object] "State Data"
* @param hash [string] "Hash"
*/
function _renderState(data, hash) {
// Update DOM
if (typeof data !== "undefined") {
for (var key in options.target) {
if (options.target.hasOwnProperty(key) && data.hasOwnProperty(key)) {
$(options.target[key]).html(data[key]);
}
}
}
}
/**
* @method private
* @name _saveState
* @description Saves the current state
*/
function _saveState() {
// Save state data before updating history
var data = [];
for (var key in options.target) {
if (options.target.hasOwnProperty(key)) {
data[key] = $(options.target[key]).html();
}
}
// Update state
history.replaceState({
url: currentURL,
data: data,
scroll: $window.scrollTop()
}, "state-"+currentURL, currentURL);
}
function _updateProgress(percent) {
}
/**
* @method private
* @name _unescape
* @description Unescapes HTML
* @param text [string] "Text to unescape"
*/
function _unescape(text) {
return text.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/ /g, " ")
.replace(/&/g, "&")
.replace(/"/g, '"')
.replace(/'/g, "'");
}
/**
* @method private
* @name _track
* @description Pushes new page view to the Google Analytics (Legacy or Universal)
* @param url [string] "URL to track"
*/
function _track(url) {
// Strip domain
url = url.replace(window.location.protocol + "//" + window.location.host, "");
if (options.tracking.legacy) {
// Legacy Analytics
window._gaq = window._gaq || [];
window._gaq.push(["_trackPageview", url]);
} else {
// Universal Analytics
if (options.tracking.manager) {
// Tag Manager
var page = {};
page[options.tracking.variable] = url;
window.dataLayer = window.dataLayer || [];
// Push new url to varibale then tracking event
window.dataLayer.push(page);
window.dataLayer.push({ 'event': options.tracking.event });
} else {
// Basic
if (typeof ga === "function") {
ga('send', 'pageview', url);
}
// Specific tracker - only needed if using mutiple and/or tag manager
//var t = ga.getAll();
//ga(t[0].get('name')+'.send', 'pageview', '/mimeo/');
}
}
}
/**
* @method private
* @name _getQueryParams
* @description Returns keyed object containing all GET query parameters
* @param url [string] "URL to parse"
* @return [object] "Keyed query params"
*/
function _getQueryParams(url) {
var params = {},
parts = url.slice( url.indexOf("?") + 1 ).split("&");
for (var i = 0; i < parts.length; i++) {
var part = parts[i].split("=");
params[ part[0] ] = part[1];
}
return params;
}
$.pronto = function(method) {
if (pub[method]) {
return pub[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return _init.apply(this, arguments);
}
return this;
};
})(jQuery, this);