-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.njax.js
1258 lines (1066 loc) · 38.9 KB
/
jquery.njax.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* NJAX is "Navigation in AJAX".
*
* Allows browsers to navigate your page without doing full page loads,
* but rather making AJAX requests and injecting responses into the body
* using history.pushState() functionality to manipulate the browser's
* addres bar.
*
* Greatly speeds up navigation.
*
* Very similar, and in fact greatly based on PJAX <https://github.com/defunkt/jquery-pjax>
* with some added functionality.
*
* @author Michał Dudek <[email protected]>
* @copyright Copyright (c) 2013, Neverbland <http://www.neverbland.com>
* @license MIT
*/
/*global jQuery*/
(function($, window, document, undefined) {
'use strict';
/***********************************************
* NJAX PRIVATE METHODS AND VARIABLES
***********************************************/
// prepare some variables
var
/**
* Dictionary of default options.
*
* Can be accessed publicly by $.njax.defaults
* e.g. $.njax.defaults.target = '#content-wrap'
*
* @type {Object}
*/
defaults = {
/**
* Should a new state be pushed? Usually yes, but not for history navigation.
*
* @type {Boolean}
*/
pushState : true,
/**
* Target where the received content will be inserted.
*
* @type {String} CSS selector.
*/
target : '#content',
/**
* After loading the new page should it scroll to top of the target?
*
* If {Number} given then it will be treated as offset/margin to scrolling.
*
* @type {Boolean|Number}
*/
scrollToTarget : false,
/**
* Speed at which the scroll to target should animate.
*
* @type {Number}
*/
scrollSpeed : 200,
/**
* Method of inserting the new content.
*
* One of the following : 'insert' (default), 'prepend', 'append', 'replace'.
*
* @type {String}
*/
insert : 'insert',
/**
* If set to true then all appended javascripts will be ignored and no njax modules executed.
*
* @type {Boolean}
*/
noScripts : false,
/**
* Format of the response.
*
* @type {String} Either 'html' or 'json'.
*/
format : 'json',
/**
* Fragment of the received page that should be inserted into the page.
*
* @type {String} CSS selector.
*/
fragment : null,
/**
* Similar to fragment but instead of inserting a single fragment it will insert the specific elements targeted by the given selector.
*
* So for example if you want to append new items to a list specify a selector for them.
*
* Takes precedence before 'fragment'.
*
* @type {String} CSS selector.
*/
elements : null,
/**
* Filter response manually with a callback function.
*
* @type {Function}
*/
filterResponse : null,
/**
* Name of the partial that the server should render.
*
* @type {String}
*/
partial : null,
/**
* Title of the page - the HTML title will be changed upon receiving successful response from the server.
*
* @type {String}
*/
title : document.title,
/**
* Timeout (in ms) for the request.
*
* @type {Number}
*/
timeoutTime : 60000,
/**
* Callback called when starting njax request.
*
* @param {Event} ev Start event.
*/
start : function(ev) {
$.noop(ev);
},
/**
* Callback called when njax request has been finished and fully handled.
*
* @param {Event} ev Start event.
*/
end : function(ev) {
$.noop(ev);
},
/**
* Callback called when njax request responded with an error.
*
* @param {String} url URL of the request.
* @param {Object} options Options for the request.
* @param {jqXHR} xhr jQuery XHR object.
* @param {String} status Status of the request.
* @param {String} error Error message.
*/
error : function(ev) {
$.noop(ev);
},
/**
* Callback called when njax request was successful.
*
* NOTE: This doesn't override the njax behavior - inserting the content, changing the page title, etc, are still handled by internal code.
*
* @param {Object} data Data returned from the server.
* @param {Object} response Parsed response data from the server (including content, page title, partial).
* @param {String} url URL of the request.
* @param {Object} options Options for the request.
* @param {jqXHR} xhr jQuery XHR object.
* @param {String} status Status of the request.
*/
success : function(ev) {
$.noop(ev);
},
/**
* Callback called when the njax request timed out.
*
* @param {String} url URL of the request.
* @param {Object} options Options for the request.
* @param {jqXHR} xhr jQuery XHR object.
* @param {Object} settings XHR settings.
*/
timeout : function(ev) {
$.noop(ev);
}
},
/**
* Window object wrapped in jQuery
*
* @type {jQuery}
*/
$win = $(window),
/**
* Document object wrapped in jQuery
*
* @type {jQuery}
*/
//$doc = $(document),
/**
* Head element wrapped in jQuery.
*
* @type {jQuery}
*/
$head = $('head'),
/**
* Body element wrapped in jQuery
*
* @type {jQuery}
*/
$body = $(document.body),
/**
* Collection of body and html elements, used by animateIntoView().
*
* @type {jQuery}
*/
$bodyAndHtml = $body.add('html'),
/**
* Is njax supported by the browser or not?
*
* @type {Boolean}
*/
supported = false,
/**
* History manager.
*
* Referenced here for better minification, but also possibility of later injecting History.js.
*
* @type {history}
*/
history = window.history,
/**
* Current XmlHttpRequest.
*
* @type {jqXHR}
*/
currentXhr,
/**
* Last njax request.
*
* @type {Object}
*/
last,
/**
* Timeout timer.
*/
timeoutTimer,
/**
* Helper variable that informs other handlers is the current handling of events silent.
*
* Set to true to ignore initial page load popstate event.
*
* @type {Boolean}
*/
silent = true,
/**
* Cache with various info about states.
*
* @type {Object}
*/
cache = {},
/**
* Stores information about loaded CSS files.
*
* @type {Object}
*/
loadedCss = {},
/**
* Stores information about loaded JavaScript files.
*
* @type {Object}
*/
loadedJavaScript = {},
/**
* All registered JavaScript modules, by js file URL.
*
* @type {Object}
*/
javaScriptModules = {},
/**
* List of currently loaded JavaScript modules.
*
* @type {Array}
*/
currentJavaScriptModules = [],
/**
* URL of a currently executed/eval'd script.
*
* Used by JavaScript management functions to properly assign modules to their owning files.
*
* @type {String}
*/
currentJavaScriptUrl = null,
/**
* Data about the current state.
*
* @type {Object}
*/
currentState = {
title : document.title
},
/***********************************************
* PRIVATE NJAX FUNCTIONS
***********************************************/
request = function(url, target, options) {
if (!supported) {
window.location.href = url;
return;
}
// URL is required
if (!url) {
throw new TypeError('No url given for njax request');
}
target = target || $.njax.defaults.target;
if (typeof target !== 'string') {
throw new TypeError('Njax request requires target to be a string selector, "' + typeof(target) + '" given.');
}
// target is required
var $target = $(target).eq(0);
//_target = target; // need to store original target value for later reference
if (!$target.length) {
throw new TypeError('Njax request requires a selector for an existing target, "' + target + '" given.');
}
// merge the options with defaults
options = $.extend(true, {}, $.njax.defaults, options);
// cancel current XmlHttpRequest, if any
if (currentXhr && currentXhr.readyState < 4) {
currentXhr.onreadystatechange = $.noop;
currentXhr.abort();
}
// store the current state data (can be customized by application)
var globalState = getGlobalState();
// make the XmlHttpRequest to get the page
currentXhr = $.ajax({
url : url,
dataType : options.format === 'html' ? 'html' : 'json',
/**
* Executed before njax request has been sent.
*
* @param {jqXHR} xhr
* @param {Object} settings
*
* @triggers njax:start On target element.
* @triggers njax:timeout On target element when the request times out.
*/
beforeSend : function(xhr, settings) {
// set some headers for the request
xhr.setRequestHeader('X-NJAX', 'true');
xhr.setRequestHeader('X-NJAX-Format', options.format);
if (options.fragment) {
xhr.setRequestHeader('X-NJAX-Fragment', options.fragment);
}
if (options.partial) {
xhr.setRequestHeader('X-NJAX-Partial', options.partial);
}
// trigger the loading event
if (trigger($target, 'njax:start', [url, options, xhr, settings], options.start)) {
xhr.abort();
return false;
}
// reset the last stored request
last = null;
// create timeout handling
if (options.timeoutTime > 0) {
timeoutTimer = setTimeout(function() {
// abort the request
xhr.abort();
// and trigger the timeout event
trigger($target, 'njax:timeout', [url, options, xhr, settings], options.timeout);
}, options.timeoutTime);
}
},
success : function(data, status, xhr) {
// make this process silent
silent = true;
// hold some parsed response data in this variable
var response = {
$content : $(),
url : xhr.getResponseHeader('X-NJAX-Display-URL') || url,
title : xhr.getResponseHeader('X-NJAX-Title') || options.title,
partial : xhr.getResponseHeader('X-NJAX-Partial') || null,
data : $.parseJSON(xhr.getResponseHeader('X-NJAX-Data')) || {},
css : [],
js : []
};
/*
* PARSE RESPONSE TO OBJECT
*/
if (options.format === 'html') {
// HTML response
response.$content = $($.trim(data));
var $title = selectAll(response.$content, 'title');
if ($title.length) {
response.title = $title.text();
}
// parse the added CSS files
selectAll(response.$content, 'link[rel="stylesheet"]').each(function() {
var $tag = $(this),
url = $tag.attr('href');
if (!url) {
return true; // continue
}
response.css.push({
url : url,
media : $tag.attr('media') || 'all'
});
// no longer keep it in the code so that the browser won't use it either
$tag.remove();
});
// parse the added JS files
selectAll(response.$content, 'script[src]').each(function() {
var $tag = $(this),
url = $tag.attr('src');
if (!url) {
return true; // continue
}
response.js.push({
url : url
});
$tag.remove();
});
} else {
// JSON response
response.$content = $($.trim(data.content));
response.js = data.js || [];
response.css = data.css || [];
}
/*
* FILTER THE RESPONSE CONTENT
* based on given options
*/
if (typeof options.filterResponse === 'function') {
// use custom function
response.$content = options.filterResponse(response.$content);
} else if (options.elements) {
// select specific elements
var $elements = response.$content.filter(options.elements);
if (!$elements.length) {
$elements = response.$content.find(options.elements);
}
response.$content = $elements;
} else if (options.fragment) {
// specific fragment
var $fragment = response.$content.filter(options.fragment);
if (!$fragment.length) {
$fragment = response.$content.find(options.fragment);
}
response.$content = $fragment.html() || '';
}
/*
* PUSH STATE MAGIC
*/
storeCurrentState($.extend(true, {}, {
target : target
}, globalState));
// push new state
if (options.pushState) {
pushState(response.url, response.title, {
target : target,
// cloning options manually because only serializable options can be stored in state (no functions)
options : {
partial : options.partial,
fragment : options.fragment
}
});
}
/*
* INSERT CONTENT
*/
unloadJavaScriptModules();
if (options.insert === 'append') {
// append to target
$target.append(response.$content);
} else if (options.insert === 'prepend') {
// prepend to target
$target.prepend(response.$content);
} else if (options.insert === 'replace') {
// replace the target
var $replaceWith = response.$content;
$target.replaceWith($replaceWith);
$target = $replaceWith;
} else {
// simply insert to the target
$target.html(response.$content);
}
// load the attached CSS files
loadCss(response.css);
var onSucess=function(){
// trigger success event
trigger($target, 'njax:success', [response, data, url, options, xhr, status], options.success);
};
// unload previous modules
// and load the attached JS files
if (!options.noScripts) {
loadJavaScript(response.js,onSucess);
}else{
onSucess();
}
// track the pageview in Google Analytics
if (window._gaq !== undefined) {
window._gaq.push(['_trackPageview']);
}
// if all done then scroll to target (if so requested)
if (options.scrollToTarget) {
animateIntoView($target, options.scrollSpeed, options.scrollToTarget);
}
// store this request params so we will be able to reload the page using njax
last = {
url : url,
target : target,
options : options
};
// turn off silence
silent = false;
},
/**
* Executed when the njax request responds with an error.
*
* @param {jqXHR} xhr
* @param {Number} status HTTP response code.
* @param {String} error Error message / type.
*
* @triggers njax:error On target element.
*/
error : function(xhr, status, error) {
// ignore aborts
if (error === 'abort') {
return;
}
silent = true;
/*
* PUSH STATE MAGIC
*/
storeCurrentState($.extend(true, {}, {
target : target
}, globalState));
// push new state
if (options.pushState) {
pushState(url, options.title, {
target : target,
// cloning options manually because only serializable options can be stored in state (no functions)
options : {
partial : options.partial,
fragment : options.fragment
}
});
}
// trigger error event
trigger($target, 'njax:error', [url, options, xhr, status, error], options.error);
// turn off silence
silent = false;
},
/**
* Executed when everything has been completed.
*
* @param {jqXHR} xhr
* @param {Number} status HTTP response code.
*
* @triggers njax:end On target element.
*/
complete : function(xhr, status) {
clearTimeout(timeoutTimer);
silent = false;
trigger($target, 'njax:end', [url, options, xhr, status], options.end);
}
});
return currentXhr;
},
/**
* Adds the passed CSS files into the page.
*
* @param {Array} files Array of CSS files.
*/
loadCss = function(files) {
$.each(files, function(i, css) {
// if already loaded before then don't load again
if (loadedCss[css.url] !== undefined) {
return true;
}
// create a link tag and append it to head
loadedCss[css.url] = $('<link />', {
rel : 'stylesheet',
href : css.url,
media : css.media
}).appendTo($head);
});
},
/**
* Adds the passed JavaScript files into the page.
*
* If it's an external file then it loads it by adding a script tag to the page's body.
* If it's a local file that was previously loaded and registered a module then it executes that module.
* If it's a local file then it loads it if it wasn't previously loaded.
*
* @param {Array} files Array of JavaScript files.
* @param {Function} callback [optional] Callback to execute when all files have been loaded.
*/
loadJavaScript = function(files, callback) {
callback = callback || $.noop;
var queue = [],
enqueued = false,
execute = function(url, code) {
// execute this code only if it is first in the queue (FIFO)
if ($.inArray(url, queue) === 0) {
// remove it from the queue and execute
queue.shift();
// store the URL for this code in a global var
// so if the code is registering a module it can properly assign it
currentJavaScriptUrl = url;
// store it in loaded javascripts
loadedJavaScript[url] = {
url : url,
local : true
};
// evaluate the code
$.globalEval(code);
// clean up
currentJavaScriptUrl = null;
} else {
// if this JavaScript isn't first in the queue yet
// then wait a bit and check again
setTimeout(function() {
execute(url, code);
}, 50);
}
if (!queue.length) { //empty queue means that we've finished
callback.apply(this);
}
};
$.each(files, function(i, js) {
// handle script from external source
if (!isLocalUrl(js.url)) {
// if already loaded then potentially load any modules in that file
// and go to the next one
if (loadedJavaScript[js.url] !== undefined) {
loadJavaScriptModulesFromUrl(js.url);
return true; // continue
}
var scriptTag = document.createElement('script');
document.body.appendChild(scriptTag);
scriptTag.onload = function() {
execute(js.url, 'false'); // dummy js but mark as loaded
};
scriptTag.src = js.url;
enqueued = true;
queue.push(js.url);
return true; // continue
}
// handle modules in local scripts that have already been loaded previously
// scripts with no modules aren't re-executed
if (loadedJavaScript[js.url] !== undefined) {
loadJavaScriptModulesFromUrl(js.url);
return true; // continue
}
enqueued = true;
// parse files that haven't been loaded yet
queue.push(js.url);
$.ajax({
url : js.url,
dataType : 'text',
success : function(code) {
execute(js.url, code);
},
error : function() {
execute(js.url, '');
}
});
});
if (!enqueued) { //no jobs were enqueued, we are done here
callback.apply(this);
}
},
/**
* Load JavaScript modules previously registered in the file from the given URL.
*
* Returns number of modules loaded.
*
* @param {String} url JavaScript file URL.
* @return {Number}
*/
loadJavaScriptModulesFromUrl = function(url) {
if (javaScriptModules[url] === undefined) {
return 0;
}
var loaded = 0;
$.each(javaScriptModules[url], function(i, module) {
currentJavaScriptModules.push(module);
module.load();
loaded++;
});
return loaded;
},
/**
* Unloads all currently registered JavaScript modules.
*/
unloadJavaScriptModules = function() {
$.each(currentJavaScriptModules, function(i, module) {
module.unload();
});
// reset
currentJavaScriptModules = [];
},
/**
* Registers JavaScript module.
*
* @param {Function} onLoadFn [optional]
* @param {Function} onUnloadFn [optional]
*/
registerJavaScript = function(onLoadFn, onUnloadFn) {
var module = {
load : typeof onLoadFn === 'function' ? onLoadFn : $.noop,
unload : typeof onUnloadFn === 'function' ? onUnloadFn : $.noop
};
var guessedUrl = false;
// try to figure out current javascript url if it's not set
// this only happens on full page load
if (!currentJavaScriptUrl) {
// so when script tags are loaded in an order the DOM after that script does not exist yet (I think.... fingers crossed)
// therefore if we select last known script tag on the page, it will be the script tag of currently parsed JS
// but it also requires `$.njax()` calls to not be wrapped in document.ready callbacks, otherwise shit will break (badly?)
var $lastScript = $('script[src]').last();
if ($lastScript.length) {
currentJavaScriptUrl = $lastScript.attr('src');
guessedUrl = true;
}
}
// and if we can read the URL from which this module is executed
// then make sure it's assigned to it
if (currentJavaScriptUrl) {
if (javaScriptModules[currentJavaScriptUrl] === undefined) {
javaScriptModules[currentJavaScriptUrl] = [];
}
javaScriptModules[currentJavaScriptUrl].push(module);
}
// cleanup after guessing
if (guessedUrl) {
currentJavaScriptUrl = null;
}
// register it in currently running modules
// and finally automatically run this javascript
currentJavaScriptModules.push(module);
module.load();
},
/**
* Reloads the current page, ie. repeats the last njax call.
*/
reload = function() {
// if no last request stored then simply reload the page
if (!last) {
window.location.reload();
}
request(last.url, last.target, last.options);
},
/**
* Wrapper function around history.pushState() that retrieves the new state and stores it in currentState as well as returning it.
*
* @param {String} url URL to be displayed in the browser's address bar.
* @param {String} title Page title that you may want to set.
* @param {Object} data [optional] Any additional state data.
* @return {Object} New state.
*/
pushState = function(url, title, data) {
title = $.trim(title).length ? title : null;
data = data || {};
var newState = $.extend(true, {}, {
id : createId(),
scrollTop : $win.scrollTop(),
url : url,
title : title
}, data);
history.pushState(newState, title, url);
// set document title explicitly as pushState no longer does that in new browsers
document.title = title;
currentState = newState;
return currentState;
},
/**
* Updates the current state info in history.
*
* @param {Object} data [optional] Any additional state data.
*/
storeCurrentState = function(data) {
var newState = $.extend(true, {}, currentState, {
id : currentState.id || createId(),
scrollTop : $win.scrollTop(),
url : window.location.pathname + window.location.search
}, data);
history.replaceState(newState, currentState.title);
// set document title explicitly as replaceState no longer does that in new browsers
document.title = currentState.title;
currentState = newState;
},
/**
* Triggers a custom event on the given element with attached data.
*
* @param {jQuery} $el jQuery Element.
* @param {String} type Event type/name.
* @param {Array} args Arguments passed to event listeners.
* @param {Function} fn [optional] Additional listener to be registered for this event and unregistered immediately after calling it.
* @return {Boolean} Is default prevented?
*/
trigger = function($el, type, args, fn) {
// if additional function passed then simply bind it as listener
if (typeof fn === 'function') {
$el.on(type + '.njaxtrigger', fn);
}
var ev = $.Event(type, {
relatedTarget : $el
});
$el.trigger(ev, args);
// unbind the previously bound listener
$el.off(type + '.njaxtrigger');
return ev.isDefaultPrevented();
},
/**
* Checks if the event (usually a click event) is a qualified njax event.
*
* ie. if the njax-related code should be executed. This is to help simulate native browser behavior.
* It checks the following:
* - if the modifier button (cmd, ctrl, alt, shift) was pressed during the event
* - if the protocol and host of the link match the current
* - if the link isn't only a hash change
*
* @param {Event} ev
* @return {Boolean} If true then you should proceed with executing njax related code.
*/
isNjaxEvent = function(ev) {
var link = ev.currentTarget;
// if modifier key pressed then ignore the njax functionality
if (ev.which > 1 || ev.metaKey || ev.ctrlKey || ev.altKey || ev.shiftKey) {
return false;
}
// ignore cross origin links
if (window.location.protocol !== link.protocol || window.location.host !== link.host) {
return false;
}
// ignore hashes on the same page
if (link.hash && link.href.replace(link.hash, '') === window.location.href.replace(window.location.hash, '')) {
return false;
}
// ignore empty hash "foo.html#"
if (link.href === '#' || link.href === window.location.href + '#') {
return false;
}
return true;
},
/**
* Checks if the given URL is local to the page (served from the same server with the same protocol)
*
* @param {String} url
* @return {Boolean}
*/
isLocalUrl = function(url) {
var link = parseUrl(url);
return ((link.protocol === window.location.protocol) && (link.host === window.location.host));
},
/**
* Parses the given URL to more easily accessible object of URL parts.
*
* @param {String} url
* @return {Object}
*/
parseUrl = function(url) {