This repository was archived by the owner on May 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathextractCSS.js
277 lines (230 loc) · 6.46 KB
/
extractCSS.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
(function (global, doc) {
var html = doc.documentElement;
var width, height;
var options = global.extractCSSOptions;
var matchMQ, required;
var stylesheets = [];
var mediaStylesheets = [];
var left;
var isRunning;
if (options) {
if ("matchMQ" in options) {
matchMQ = options.matchMQ;
}
if ("required" in options) {
required = options.required;
required = required.map(function (string) {
return new RegExp(string, "i");
});
}
}
function init(force) {
if (isRunning && !force) {
return;
}
isRunning = true;
var links = doc.querySelectorAll("link");
var cssLinksStillLoading = Array.prototype.slice.call(links).filter(function (link) {
if (link.rel == "preload" && link.as == "style") {
return true;
}
return false;
});
if (cssLinksStillLoading.length > 0) {
setTimeout(function () {
init(true);
}, 50);
return;
}
width = html.offsetWidth;
height = global.innerHeight;
mediaStylesheets = Array.prototype.slice.call(doc.styleSheets).filter(function (stylesheet) {
return (!stylesheet.media.length || stylesheet.media[0] == "screen" || stylesheet.media[0] == "all");
});
left = mediaStylesheets.slice(0);
var base = global.location.href.replace(/\/[^/]+$/, "/");
var host = global.location.protocol + "//" + global.location.host;
mediaStylesheets.forEach(function (stylesheet) {
if (stylesheet.href) {
fetchStylesheet(stylesheet.href, function (text) {
var index = left.indexOf(stylesheet);
if (index > -1) {
left.splice(index, 1);
}
text = text.replace(/\/\*[\s\S]+?\*\//g, "").replace(/[\n\r]+/g, "").replace(/url\((["']|)(\.\.\/[^"'\(\)]+)\1\)/g, function (m, quote, url) {
return "url(" + quote + pathRelativeToPage(base, stylesheet.href, url) + quote + ")";
});
text = text.replace(/@charset "[^"]*";/gm, "");
stylesheets.push(text);
if (left.length === 0) {
complete();
}
});
}
else {
var index = left.indexOf(stylesheet);
if (index > -1) {
left.splice(index, 1);
}
if (left.length === 0) {
complete();
}
}
});
function complete() {
var elements = false;
// if viewport height is forced
// define elements to check seletors against
if (html.offsetHeight != height) {
elements = Array.prototype.slice.call(doc.getElementsByTagName("*")).filter(function (element) {
return (element.getBoundingClientRect().top < height);
});
}
var CSS = stylesheets.map(function (css) {
return outputRules(filterCSS(css, elements));
}).join("");
console.log('_extractedcss', {css: CSS });
isRunning = false;
}
}
function outputRules(rules) {
return rules.map(function (rule) {
return rule.selectors.join(",") + "{" + rule.css + "}";
}).join("");
}
function matchSelectors(selectors, elements) {
return selectors.map(function (selector) {
// strip comments
return selector.replace(/\/\*[\s\S]+?\*\//g, "").replace(/(?:^\s+)|(?:\s+$)/g, "");
}).filter(function (selector) {
if (!selector || selector.match(/@/)) {
return false;
}
if (required) {
var found = required.some(function (reg) {
return reg.test(selector);
});
if (found) {
return true;
}
}
if (selector.indexOf(":") > -1) {
// strip pseudo-classes that may not be directly selectable or can change on userinteraction
selector = selector.replace(/(?:::?)(?:after|before|link|visited|hover|active|focus|selection|checked|selected|optional|required|invalid|valid|in-range|read-only|read-write|target|(?:-[a-zA-Z-]+))\s*$/g, "");
}
if (selector.length == 0) {
return true;
}
var matches = [];
try {
matches = doc.querySelectorAll(selector);
}
catch(e){}
var i = 0;
var l = matches.length;
if (l) {
if (elements) {
while (i < l) {
if (elements.indexOf(matches[i++]) > -1) {
return true;
}
}
return false;
}
return true;
}
return false;
});
}
function filterCSS(css, elements) {
var rules = parseRules(css),
matchedRules = [];
rules.forEach(function (rule) {
var matchingSelectors = [];
var atRuleMatch = rule.selectors[0].match(/^\s*(@[a-z\-]+)/);
if (rule.selectors) {
if (atRuleMatch) {
switch (atRuleMatch[1]) {
case "@font-face":
matchingSelectors = ["@font-face"];
break;
case "@media":
var mq;
if (matchMQ) {
var widths = rule.selectors[0].match(/m(?:ax|in)-width:[^)]+/g);
var pair;
if (widths) {
mq = {};
while (widths.length) {
pair = widths.shift().split(/:\s?/);
mq[pair[0]] = parseInt(pair[1]);
}
}
}
if (!matchMQ || !mq || ((!("min-width" in mq) || mq["min-width"] <= width) && (!("max-width" in mq) || mq["max-width"] >= width))) {
var matchedSubRules = filterCSS(rule.css, elements);
if (matchedSubRules.length) {
matchingSelectors = rule.selectors;
rule.css = outputRules(matchedSubRules);
}
}
break;
}
}
else {
matchingSelectors = matchSelectors(rule.selectors, elements);
}
}
if (matchingSelectors.length) {
rule.selectors = matchingSelectors;
matchedRules.push(rule);
}
});
return matchedRules;
}
function parseRules(css) {
var matches = css.replace(/\n+/g, " ").match(/(?:[^{}]+\s*\{[^{}]+\})|(?:[^{}]+\{\s*(?:[^{}]+\{[^{}]+\})+\s*\})/g);
var rules = [];
if (matches) {
matches.forEach(function (match) {
var rule = parseRule(match);
if (rule) {
rules.push(rule);
}
});
}
return rules;
}
function parseRule(rule) {
var match = rule.match(/^\s*([^{}]+)\s*\{\s*((?:[^{}]+\{[^{}]+\})+|[^{}]+)\s*\}$/);
return {
selectors: match && match[1].split(/\s*,\s*/),
css: match && match[2]
};
}
function pathRelativeToPage(basepath, csspath, sourcepath) {
while (sourcepath.indexOf("../") === 0) {
sourcepath = sourcepath.slice(3);
csspath = csspath.replace(/\/[^/]+\/[^/]*$/, "/");
}
var path = csspath + sourcepath;
return (path.indexOf(basepath) === 0) ? path.slice(basepath.length) : path;
}
function fetchStylesheet(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.onload = function () {
callback(xhr.responseText);
};
xhr.send(null);
return xhr;
}
if (doc.readyState != "complete") {
global.addEventListener("load", function () {
init();
}, false);
}
else {
init();
}
}(this, document));