-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathContent-Visibility.js
More file actions
352 lines (305 loc) · 11.3 KB
/
Content-Visibility.js
File metadata and controls
352 lines (305 loc) · 11.3 KB
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
// Detect elements with content-visibility: auto and analyze optimization opportunities
function detectContentVisibility() {
// Create an object to store the results
const results = {
autoElements: [],
hiddenElements: [],
visibleElements: [],
nodeArray: [],
};
// Get the name of the node
function getName(node) {
const name = node.nodeName;
return node.nodeType === 1 ? name.toLowerCase() : name.toUpperCase().replace(/^#/, "");
}
// Get the selector for an element
function getSelector(node) {
let sel = "";
try {
while (node && node.nodeType !== 9) {
const el = node;
const part = el.id
? "#" + el.id
: getName(el) +
(el.classList &&
el.classList.value &&
el.classList.value.trim() &&
el.classList.value.trim().length
? "." + el.classList.value.trim().replace(/\s+/g, ".")
: "");
if (sel.length + part.length > 100 - 1) return sel || part;
sel = sel ? part + ">" + sel : part;
if (el.id) break;
node = el.parentNode;
}
} catch {
// Do nothing...
}
return sel;
}
// Check if element is in viewport
function isInViewport(element) {
const rect = element.getBoundingClientRect();
return (
rect.top < window.innerHeight &&
rect.bottom > 0 &&
rect.left < window.innerWidth &&
rect.right > 0
);
}
// Get element dimensions and position
function getElementInfo(node) {
const rect = node.getBoundingClientRect();
const cs = window.getComputedStyle(node);
return {
selector: getSelector(node),
contentVisibility: cs["content-visibility"],
containIntrinsicSize: cs["contain-intrinsic-size"] || "not set",
width: Math.round(rect.width),
height: Math.round(rect.height),
top: Math.round(rect.top + window.scrollY),
inViewport: isInViewport(node),
};
}
// Recursively find all elements with content-visibility
function findContentVisibilityElements(node) {
const cs = window.getComputedStyle(node);
const cv = cs["content-visibility"];
if (cv && cv !== "visible") {
const info = getElementInfo(node);
if (cv === "auto") {
results.autoElements.push(info);
results.nodeArray.push(node);
} else if (cv === "hidden") {
results.hiddenElements.push(info);
}
}
for (let i = 0; i < node.children.length; i++) {
findContentVisibilityElements(node.children[i]);
}
}
// Run the detection
findContentVisibilityElements(document.body);
// Display results
console.group("🔍 Content-Visibility Detection");
if (results.autoElements.length === 0 && results.hiddenElements.length === 0) {
console.log("%cNo content-visibility usage found.", "color: orange; font-weight: bold;");
console.log("");
console.log("💡 Consider applying content-visibility: auto to:");
console.log(" • Footer sections");
console.log(" • Below-the-fold content");
console.log(" • Long lists or card grids");
console.log(" • Tab content that is not initially visible");
console.log(" • Accordion/collapsible content");
} else {
// Auto elements
if (results.autoElements.length > 0) {
console.group("✅ content-visibility: auto");
console.log(`Found ${results.autoElements.length} element(s)`);
console.table(results.autoElements);
console.groupEnd();
}
// Hidden elements
if (results.hiddenElements.length > 0) {
console.group("🔒 content-visibility: hidden");
console.log(`Found ${results.hiddenElements.length} element(s)`);
console.table(results.hiddenElements);
console.groupEnd();
}
// Check for missing contain-intrinsic-size
const missingIntrinsicSize = results.autoElements.filter(
(el) => el.containIntrinsicSize === "not set" || el.containIntrinsicSize === "none",
);
if (missingIntrinsicSize.length > 0) {
console.group("⚠️ Missing contain-intrinsic-size");
console.log(
"%cThese elements lack contain-intrinsic-size, which may cause layout shifts:",
"color: #f59e0b; font-weight: bold",
);
console.table(
missingIntrinsicSize.map((el) => ({
selector: el.selector,
height: el.height + "px",
})),
);
console.log("");
console.log("💡 Add contain-intrinsic-size to prevent CLS:");
console.log(" contain-intrinsic-size: auto 500px;");
console.groupEnd();
}
// Nodes for inspection
console.group("🔎 Elements for inspection");
console.log("Click to expand and inspect in Elements panel:");
results.nodeArray.forEach((node, i) => {
console.log(`${i + 1}. `, node);
});
console.groupEnd();
}
console.groupEnd();
return results;
}
// Analyze opportunities for content-visibility optimization
// Options:
// - threshold: distance from viewport bottom to consider "offscreen" (default: 0)
// - minHeight: minimum element height in px (default: 100)
// - minChildren: minimum child elements to be considered (default: 5)
function analyzeContentVisibilityOpportunities(options = {}) {
const { threshold = 0, minHeight = 100, minChildren = 5 } = options;
const viewportHeight = window.innerHeight;
const opportunities = [];
const processedElements = new Set();
function getSelector(node) {
let sel = "";
try {
while (node && node.nodeType !== 9) {
const el = node;
const name = el.nodeName.toLowerCase();
const part = el.id
? "#" + el.id
: name +
(el.classList && el.classList.value && el.classList.value.trim()
? "." + el.classList.value.trim().split(/\s+/).slice(0, 2).join(".")
: "");
if (sel.length + part.length > 80) return sel || part;
sel = sel ? part + ">" + sel : part;
if (el.id) break;
node = el.parentNode;
}
} catch {}
return sel;
}
function estimateRenderSavings(childCount) {
const baseMs = childCount * 0.2;
if (baseMs < 5) return "Low (~" + baseMs.toFixed(1) + "ms)";
if (baseMs < 20) return "Medium (~" + baseMs.toFixed(1) + "ms)";
return "High (~" + baseMs.toFixed(1) + "ms)";
}
function isAncestorProcessed(el) {
let parent = el.parentElement;
while (parent) {
if (processedElements.has(parent)) return true;
parent = parent.parentElement;
}
return false;
}
function analyzeElement(el) {
// Skip already processed or descendant of processed
if (processedElements.has(el) || isAncestorProcessed(el)) return;
const rect = el.getBoundingClientRect();
const cs = window.getComputedStyle(el);
// Skip if already using content-visibility
if (cs["content-visibility"] && cs["content-visibility"] !== "visible") return;
// Skip elements not meeting size criteria
if (rect.height < minHeight || rect.width === 0) return;
// Check if element is below the viewport + threshold
const distanceFromViewport = rect.top - viewportHeight;
if (distanceFromViewport < threshold) return;
const childCount = el.querySelectorAll("*").length;
// Skip elements with too few children
if (childCount < minChildren) return;
processedElements.add(el);
opportunities.push({
selector: getSelector(el),
height: Math.round(rect.height) + "px",
distanceFromViewport: Math.round(distanceFromViewport) + "px",
childElements: childCount,
estimatedSavings: estimateRenderSavings(childCount),
element: el,
});
}
// Walk all elements in the DOM
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, null, false);
while (walker.nextNode()) {
analyzeElement(walker.currentNode);
}
// Sort by child count (highest impact first)
opportunities.sort((a, b) => b.childElements - a.childElements);
// Display results
console.group("💡 Content-Visibility Opportunities");
console.log(
`%cSettings: threshold=${threshold}px, minHeight=${minHeight}px, minChildren=${minChildren}`,
"color: #888;",
);
console.log("");
if (opportunities.length === 0) {
console.log("%c✅ No opportunities found with current settings.", "color: #22c55e; font-weight: bold");
console.log("Try adjusting: analyzeContentVisibilityOpportunities({ threshold: -200, minHeight: 50, minChildren: 3 })");
} else {
console.log(
`%cFound ${opportunities.length} element(s) that could benefit from content-visibility: auto`,
"font-weight: bold;",
);
console.log("");
// Show table without element reference
const tableData = opportunities.slice(0, 20).map((opportunity) => ({
selector: opportunity.selector,
height: opportunity.height,
distanceFromViewport: opportunity.distanceFromViewport,
childElements: opportunity.childElements,
estimatedSavings: opportunity.estimatedSavings,
}));
console.table(tableData);
if (opportunities.length > 20) {
console.log(`... and ${opportunities.length - 20} more elements`);
}
// Log elements for inspection
console.log("");
console.group("🔎 Elements for inspection");
opportunities.slice(0, 10).forEach((opp, i) => {
console.log(`${i + 1}. `, opp.element);
});
console.groupEnd();
console.log("");
console.group("📝 Implementation Example");
console.log("Add this CSS to optimize rendering:");
console.log("");
console.log(
"%c/* Optimize offscreen content */\n" +
".your-selector {\n" +
" content-visibility: auto;\n" +
" contain-intrinsic-size: auto 500px; /* Use actual height */\n" +
"}",
"font-family: monospace; background: #1e1e1e; color: #9cdcfe; padding: 10px; border-radius: 4px;",
);
console.groupEnd();
}
console.groupEnd();
return {
opportunities: opportunities.map((opportunity) => ({
selector: opportunity.selector,
height: opportunity.height,
distanceFromViewport: opportunity.distanceFromViewport,
childElements: opportunity.childElements,
estimatedSavings: opportunity.estimatedSavings,
})),
totalElements: opportunities.length,
highImpact: opportunities.filter((o) => o.estimatedSavings.startsWith("High")).length,
elements: opportunities.map((o) => o.element),
};
}
window.analyzeContentVisibilityOpportunities = analyzeContentVisibilityOpportunities;
// Run detection
(() => {
const cvResults = detectContentVisibility();
console.log(
"%c\n To find optimization opportunities, run: %canalyzeContentVisibilityOpportunities()",
"color: #3b82f6; font-weight: bold;",
"color: #22c55e; font-weight: bold; font-family: monospace;"
);
return {
script: "Content-Visibility",
status: "ok",
count: cvResults.autoElements.length + cvResults.hiddenElements.length,
details: {
autoCount: cvResults.autoElements.length,
hiddenCount: cvResults.hiddenElements.length,
},
items: [
...cvResults.autoElements.map(el => ({ ...el, type: "auto" })),
...cvResults.hiddenElements.map(el => ({ ...el, type: "hidden" })),
],
issues: cvResults.autoElements
.filter(el => el.containIntrinsicSize === "not set" || el.containIntrinsicSize === "none")
.map(el => ({ severity: "warning", message: `${el.selector}: missing contain-intrinsic-size (CLS risk)` })),
};
})();