forked from bgrins/devtools-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcssreload.js
54 lines (47 loc) · 1.44 KB
/
cssreload.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
// cssreload.js
// https://github.com/bgrins/devtools-snippets
// Removes then reloads all the CSS files in the current page
(function () {
function insertAfter(newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement) {
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
function reloadStyleSheet(stylesheet) {
var element = stylesheet.ownerNode;
var clone = element.cloneNode(false);
clone.href = addRandomToUrl(clone.href);
clone.addEventListener("load", function() {
if (element.parentNode) {
element.parentNode.removeChild(element);
}
});
insertAfter(clone, element);
}
function addRandomToUrl(input) {
// prevent CSS caching
var hasRnd = /([?&])_=[^&]*/,
hasQueryString = /\?/,
hasHash = /(.+)#(.+)/,
hash = null,
rnd = Math.random();
var hashMatches = input.match(hasHash);
if (hashMatches) {
input = hashMatches[1];
hash = hashMatches[2];
}
url = hasRnd.test(input) ?
input.replace(hasRnd, "$1_=" + rnd) :
input + (hasQueryString.test(input) ? "&" : "?") + "_=" + rnd;
if (hash) url += '#' + hash;
return url;
}
[].forEach.call(document.styleSheets, function(styleSheet) {
if (!styleSheet.href) return;
console.log('reload ' + styleSheet.href);
reloadStyleSheet(styleSheet);
});
})();