-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathauto_update_stylesheets.js
83 lines (67 loc) · 2.31 KB
/
auto_update_stylesheets.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
(function($) {
var initialized = null;
$.autoUpdateStylesheets = function(toggle) {
var linkElements = $('head link[rel=stylesheet]'), index = -1;
if (!initialized) {
normalizeQueryStrings();
initialized = true;
}
switch(toggle) {
case 'disable':
stop();
break;
case 'toggle':
case true:
$.autoUpdateStylesheetsTimeout ? stop() : start();
break;
default:
start();
}
function stop() {
showMessage('Stylesheets are now frozen.');
if ($.autoUpdateStylesheetsTimeout) clearTimeout($.autoUpdateStylesheetsTimeout);
$.autoUpdateStylesheetsTimeout = false;
}
function start() {
showMessage('Stylesheet changes will be reflected in real-time.');
if (!$.autoUpdateStylesheetsTimeout) $.autoUpdateStylesheetsTimeout = setTimeout(compareNextStyleSheet, 300);
}
function compareNextStyleSheet() {
if (!$.autoUpdateStylesheetsTimeout) return;
var link = getNextLinkElement(),
url = link.href.replace(/timestamp=\d+/, 'timestamp=' + new Date().getTime());
$.ajax({
url: url,
success: function(data) {
if (data != $(link).data('cachedData')) {
$(link).data('cachedData', data).attr('href', url);
}
},
complete: function() {
$.autoUpdateStylesheetsTimeout = setTimeout(compareNextStyleSheet, 300);
}
});
}
function getNextLinkElement() {
index = (index + 1) % linkElements.length;
return linkElements[index];
}
function normalizeQueryStrings() {
linkElements.each(function(i, link) {
var url = link.href;
if (url.indexOf('?') == -1) url += '?';
url += '×tamp=0';
$(link).attr('href', url);
});
}
function showMessage(message) {
var messageContainer = $('<div style="position: fixed; top: 0; padding: 15px 0; width: 100%; text-align: center;" />');
messageContainer.append('<span style="border: 1px solid #333; padding: 5px 10px; background: #cec; font-size: 14px" />');
messageContainer.children().html(message);
$('body').prepend(messageContainer);
setTimeout(function() {
messageContainer.fadeOut('slow', function() { $(this).remove() });
}, 2500);
}
}
})(jQuery);