This repository has been archived by the owner on Aug 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
enhance.js
executable file
·562 lines (522 loc) · 16.6 KB
/
enhance.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
/*
* EnhanceJS version 1.1 - Test-Driven Progressive Enhancement
* http://enhancejs.googlecode.com/
* Copyright (c) 2010 Filament Group, Inc, authors.txt
* Licensed under MIT (license.txt)
*/
(function(win, doc, undefined) {
var settings, body, fakeBody, windowLoaded, head,
docElem = doc.documentElement,
testPass = false,
mediaCookieA, mediaCookieB,
toggledMedia = [];
if(doc.getElementsByTagName){ head = doc.getElementsByTagName('head')[0] || docElem; }
else{ head = docElem; }
//test whether a media query applies
var mediaquery = (function(){
var cache = {},
testDiv = doc.createElement('div');
testDiv.setAttribute('id','ejs-qtest');
return function(q){
//check if any media types should be toggled
if (cache[q] === undefined) {
addFakeBody();
var styleBlock = doc.createElement('style');
styleBlock.type = "text/css";
head.appendChild(styleBlock);
/*set inner css text. credit: http://www.phpied.com/dynamic-script-and-style-elements-in-ie/*/
var cssrule = '@media '+q+' { #ejs-qtest { position: absolute; width: 10px; } }';
if (styleBlock.styleSheet){ styleBlock.styleSheet.cssText = cssrule; }
else { styleBlock.appendChild(doc.createTextNode(cssrule)); }
body.appendChild(testDiv);
var divWidth = testDiv.offsetWidth;
body.removeChild(testDiv);
head.removeChild(styleBlock);
removeFakeBody();
cache[q] = (divWidth == 10);
}
return cache[q];
}
})();
win.enhance = function(options) {
options = options || {};
settings = {};
// mixin settings
for (var name in enhance.defaultSettings) {
var option = options[name];
settings[name] = option !== undefined ? option : enhance.defaultSettings[name];
}
// mixin additional tests
for (var test in options.addTests) {
settings.tests[test] = options.addTests[test];
}
//add testName class immediately for FOUC prevention, remove later on fail
if (docElem.className.indexOf(settings.testName) === -1) {
docElem.className += ' ' + settings.testName;
}
//cookie names for toggled media types
mediaCookieA = settings.testName + '-toggledmediaA';
mediaCookieB = settings.testName + '-toggledmediaB';
toggledMedia = [readCookie(mediaCookieA), readCookie(mediaCookieB)];
//fallback for removing testName class
setTimeout(function(){ if(!testPass){ removeHTMLClass(); } }, 3000);
runTests();
applyDocReadyHack();
windowLoad(function() { windowLoaded = true; });
};
enhance.query = mediaquery;
enhance.defaultTests = {
getById: function() {
return !!doc.getElementById;
},
getByTagName: function() {
return !!doc.getElementsByTagName;
},
createEl: function() {
return !!doc.createElement;
},
boxmodel: function() {
var newDiv = doc.createElement('div');
newDiv.style.cssText = 'width: 1px; padding: 1px;';
body.appendChild(newDiv);
var divWidth = newDiv.offsetWidth;
body.removeChild(newDiv);
return divWidth === 3;
},
position: function() {
var newDiv = doc.createElement('div');
newDiv.style.cssText = 'position: absolute; left: 10px;';
body.appendChild(newDiv);
var divLeft = newDiv.offsetLeft;
body.removeChild(newDiv);
return divLeft === 10;
},
floatClear: function() {
var pass = false,
newDiv = doc.createElement('div'),
style = 'style="width: 5px; height: 5px; float: left;"';
newDiv.innerHTML = '<div ' + style + '></div><div ' + style + '></div>';
body.appendChild(newDiv);
var childNodes = newDiv.childNodes,
topA = childNodes[0].offsetTop,
divB = childNodes[1],
topB = divB.offsetTop;
if (topA === topB) {
divB.style.clear = 'left';
topB = divB.offsetTop;
if (topA !== topB) {
pass = true;
}
}
body.removeChild(newDiv);
return pass;
},
heightOverflow: function() {
var newDiv = doc.createElement('div');
newDiv.innerHTML = '<div style="height: 10px;"></div>';
newDiv.style.cssText = 'overflow: hidden; height: 0;';
body.appendChild(newDiv);
var divHeight = newDiv.offsetHeight;
body.removeChild(newDiv);
return divHeight === 0;
},
ajax: function() {
//factory test borrowed from quirksmode.org
var xmlhttp = false, index = -1, factory,
XMLHttpFactories = [
function() { return new XMLHttpRequest() },
function() { return new ActiveXObject("Msxml2.XMLHTTP") },
function() { return new ActiveXObject("Msxml3.XMLHTTP") },
function() { return new ActiveXObject("Microsoft.XMLHTTP") }
];
while ((factory = XMLHttpFactories[++index])) {
try { xmlhttp = factory(); }
catch (e) { continue; }
break;
}
return !!xmlhttp;
},
resize: function() {
return win.onresize != false;
},
print: function() {
return !!win.print;
}
};
enhance.defaultSettings = {
testName: 'enhanced',
loadScripts: [],
loadStyles: [],
queueLoading: true,
appendToggleLink: true,
forcePassText: 'View high-bandwidth version',
forceFailText: 'View low-bandwidth version',
tests: enhance.defaultTests,
media: {
'-ejs-desktop': enhance.query('screen and (max-device-width: 1024px)') ? 'not screen and (max-device-width: 1024px)' : 'screen',
'-ejs-handheld': 'screen and (max-device-width: 1024px)'
},
addTests: {},
alertOnFailure: false,
onPass: function(){},
onFail: function(){},
onLoadError: addIncompleteClass,
onScriptsLoaded: function(){}
};
function cookiesSupported(){
return !!doc.cookie;
}
enhance.cookiesSupported = cookiesSupported();
function forceFail() {
createCookie(settings.testName, 'fail');
win.location.reload();
}
if(enhance.cookiesSupported){ enhance.forceFail = forceFail; }
function forcePass() {
createCookie(settings.testName, 'pass');
win.location.reload();
}
if(enhance.cookiesSupported){ enhance.forcePass = forcePass; }
function reTest() {
eraseCookie(settings.testName);
win.location.reload();
}
if(enhance.cookiesSupported){ enhance.reTest = reTest; }
function addFakeBody(){
fakeBody = doc.createElement('body');
docElem.insertBefore(fakeBody, docElem.firstChild);
body = fakeBody;
}
function removeFakeBody(){
docElem.removeChild(fakeBody);
body = doc.body;
}
function runTests() {
var result = readCookie(settings.testName);
//check for cookies from a previous test
if (result) {
if (result === 'pass') {
enhancePage();
settings.onPass();
} else {
settings.onFail();
removeHTMLClass();
}
// append toggle link
if (settings.appendToggleLink) {
windowLoad(function() {
appendToggleLinks(result);
});
}
}
//no cookies - run tests
else {
var pass = true;
addFakeBody();
for (var name in settings.tests) {
pass = settings.tests[name]();
if (!pass) {
if (settings.alertOnFailure) {
alert(name + ' failed');
}
break;
}
}
removeFakeBody();
result = pass ? 'pass' : 'fail';
createCookie(settings.testName, result);
if (pass) {
enhancePage();
settings.onPass();
}
else {
settings.onFail();
removeHTMLClass();
}
if (settings.appendToggleLink) {
windowLoad(function() {
appendToggleLinks(result);
});
}
}
}
function windowLoad(callback) {
if (windowLoaded) {
callback();
} else {
var oldonload = win.onload
win.onload = function() {
if (oldonload) { oldonload(); }
callback();
}
}
}
function appendToggleLinks(result) {
if (!settings.appendToggleLink || !enhance.cookiesSupported) { return; }
if (result) {
var a = doc.createElement('a');
a.href = "#";
a.className = settings.testName + '_toggleResult';
a.innerHTML = result === 'pass' ? settings.forceFailText : settings.forcePassText;
a.onclick = result === 'pass' ? enhance.forceFail : enhance.forcePass;
doc.getElementsByTagName('body')[0].appendChild(a);
}
}
function removeHTMLClass(){
docElem.className = docElem.className.replace(settings.testName,'');
}
function enhancePage() {
testPass = true;
if (settings.loadStyles.length) {
appendStyles();
}
if (settings.loadScripts.length) {
appendScripts();
}
else{
settings.onScriptsLoaded();
}
}
//media toggling methods and storage
function toggleMedia(mediaA,mediaB){
if(readCookie(mediaCookieA) && readCookie(mediaCookieB)){
eraseCookie(mediaCookieA);
eraseCookie(mediaCookieB);
}
else{
createCookie(mediaCookieA, mediaA);
createCookie(mediaCookieB, mediaB);
}
win.location.reload();
}
enhance.toggleMedia = toggleMedia;
//return a toggled media type/query
function mediaSwitch(q){
if(toggledMedia.length == 2){
if(q == toggledMedia[0]){ q = toggledMedia[1]; }
else if(q == toggledMedia[1]){ q = toggledMedia[0]; }
}
return q;
}
function addIncompleteClass (){
var errorClass = settings.testName + '-incomplete';
if (docElem.className.indexOf(errorClass) === -1) {
docElem.className += ' ' + errorClass;
}
}
function checkifsupported(ifsupported){
if(ifsupported.constructor === Array){
var allGood = true;
for(var item in ifsupported){
if(allGood){ allGood = !!ifsupported[item]; }
}
return allGood;
}
else {
return !!ifsupported;
}
}
function appendStyles() {
var index = -1,
item;
while ((item = settings.loadStyles[++index])) {
var link = doc.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.onerror = settings.onLoadError;
if (typeof item === 'string') {
link.href = item;
head.appendChild(link);
}
else {
if(item['media']){
item['media'] = mediaSwitch(item['media']);
if(settings['media']){
if(settings['media'][item['media']] !== undefined){
item['media'] = settings['media'][item['media']];
}
}
}
if(item['excludemedia']){ item['excludemedia'] = mediaSwitch(item['excludemedia']); }
var applies = true;
if(item['media'] && item['media'] !== 'print' && item['media'] !== 'projection' && item['media'] !== 'speech' && item['media'] !== 'aural' && item['media'] !== 'braille'){
applies = mediaquery(item['media']);
}
if(applies && item['excludemedia']){
applies = !mediaquery(item['excludemedia']);
}
if (applies && item['iecondition']) {
applies = isIE(item['iecondition']);
}
if(applies && item['ifsupported'] !== undefined){
applies = checkifsupported(item['ifsupported']);
if(!applies && item['fallback'] !== undefined){
item['href'] = item['fallback'];
applies = true;
}
}
if(applies){
for (var attr in item) {
if (attr !== 'iecondition' && attr !== 'excludemedia' && attr !== 'ifsupported' && attr !== 'fallback') {
link.setAttribute(attr, item[attr]);
}
}
head.appendChild(link);
}
}
}
}
var isIE = (function() {
var cache = {},
b;
return function(condition) {
if(/*@cc_on!@*/true){return false;}
var cc = 'IE';
if(condition){
if(condition !== 'all'){ //deprecated support for 'all' keyword
if( !isNaN(parseFloat(condition)) ){
cc += ' ' + condition; //deprecated support for straight version #
}
else {
cc = condition; //recommended (conditional comment syntax)
}
}
}
if (cache[cc] === undefined) {
b = b || doc.createElement('B');
b.innerHTML = '<!--[if '+ cc +']><b></b><![endif]-->';
cache[cc] = !!b.getElementsByTagName('b').length;
}
return cache[cc];
}
})();
function appendScripts(){
settings.queueLoading ? appendScriptsSync() : appendScriptsAsync();
}
function appendScriptsSync() {
var queue = [].concat(settings.loadScripts);
function next() {
if (queue.length === 0) {
return false;
}
var item = queue.shift(),
script = createScriptTag(item),
done = false;
if(script){
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
if(next() === false){
settings.onScriptsLoaded();
}
this.onload = this.onreadystatechange = null;
}
}
head.insertBefore(script, head.firstChild);
}
else{
return next();
}
}
next();
}
function appendScriptsAsync() {
var index = -1,
item;
while ((item = settings.loadScripts[++index])) {
var script = createScriptTag(item);
if(script){
head.insertBefore(script, head.firstChild);
}
}
settings.onScriptsLoaded();
}
function createScriptTag(item) {
var script = doc.createElement('script');
script.type = 'text/javascript';
script.onerror = settings.onLoadError;
if (typeof item === 'string') {
script.src = item;
return script;
}
else {
if(item['media']){
item['media'] = mediaSwitch(item['media']);
if(settings['media']){
if(settings['media'][item['media']]){
item['media'] = settings['media'][item['media']];
}
}
}
if(item['excludemedia']){ item['excludemedia'] = mediaSwitch(item['excludemedia']); }
var applies = true;
if(item['media']){
applies = mediaquery(item['media']);
}
if(applies && item['excludemedia']){
applies = !mediaquery(item['excludemedia']);
}
if (applies && item['iecondition']) {
applies = isIE(item['iecondition']);
}
if(applies && item['ifsupported'] !== undefined){
applies = checkifsupported(item['ifsupported']);
if(!applies && item['fallback'] !== undefined){
item['src'] = item['fallback'];
applies = true;
}
}
if(applies){
for (var attr in item) {
if (attr !== 'iecondition' && attr !== 'media' && attr !== 'excludemedia' && attr !== 'ifsupported' && attr !== 'fallback') {
script.setAttribute(attr, item[attr]);
}
}
return script;
}
else{
return false;
}
}
}
/* cookie functions from quirksmode.org (modified) */
function createCookie(name, value, days) {
days = days || 90;
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
doc.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = doc.cookie.split(';');
for (var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function applyDocReadyHack() {
// via http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
// verify that document.readyState is undefined
// verify that document.addEventListener is there
// these two conditions are basically telling us
// we are using Firefox < 3.6
if (doc.readyState == null && doc.addEventListener){
// on DOMContentLoaded event, supported since ages
doc.addEventListener("DOMContentLoaded", function DOMContentLoaded(){
// remove the listener itself
doc.removeEventListener("DOMContentLoaded", DOMContentLoaded, false);
// assign readyState as complete
doc.readyState = "complete";
}, false);
// set readyState = loading or interactive
// it does not really matter for this purpose
doc.readyState = "loading";
}
}
})(window, document);