-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
832 lines (711 loc) · 25.9 KB
/
Copy pathcontent.js
File metadata and controls
832 lines (711 loc) · 25.9 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
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
/**
* Bad Page v2.1 - Optimized Performance Visualizer
*/
class BadPageAnalyzer {
constructor() {
this.metrics = {
performance: 0,
lcp: null,
fcp: null,
cls: 0,
tbt: 0
};
this.issues = [];
this.issuesByType = {
oversized: [],
cls: [],
format: [],
lazy: []
};
this.processedElements = new WeakSet();
this.overlaysVisible = true;
this.hudMinimized = false;
this.sidebarVisible = false;
this.initialized = false;
this.enabled = true; // Master on/off switch
// Keep track of LCP elements
this.lcpElements = [];
// Debounce timers
this.analysisTimer = null;
this.observerTimer = null;
// Settings
this.settings = {
performance: true,
images: true,
seo: false,
accessibility: false
};
this.init();
}
init() {
// Only initialize once
if (this.initialized) return;
this.initialized = true;
// Delay heavy operations
setTimeout(() => {
this.createHUD();
this.collectMetrics();
this.runInitialAnalysis();
this.setupListeners();
this.setupLazyObserver();
}, 100);
}
collectMetrics() {
// Only collect essential metrics
this.observeLCP();
this.observeFCP();
this.observeCLS();
}
observeLCP() {
if (typeof PerformanceObserver === 'undefined') return;
try {
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1];
if (lastEntry && lastEntry.element) {
this.metrics.lcp = Math.round(lastEntry.startTime);
// Clear previous LCP elements
this.lcpElements.forEach(el => {
if (el.badge) el.badge.remove();
if (el.element) el.element.style.border = '';
});
this.lcpElements = [];
// Mark new LCP element
this.markLCPElement(lastEntry.element);
this.updateHUDMetric('lcp', `${this.metrics.lcp}ms`);
}
});
observer.observe({ type: 'largest-contentful-paint', buffered: true });
} catch (e) {
console.log('LCP observation not supported');
}
}
observeFCP() {
if (typeof PerformanceObserver === 'undefined') return;
try {
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
const fcpEntry = entries.find(entry => entry.name === 'first-contentful-paint');
if (fcpEntry) {
this.metrics.fcp = Math.round(fcpEntry.startTime);
this.updateHUDMetric('fcp', `${this.metrics.fcp}ms`);
}
});
observer.observe({ type: 'paint', buffered: true });
} catch (e) {
console.log('FCP observation not supported');
}
}
observeCLS() {
if (typeof PerformanceObserver === 'undefined') return;
let clsValue = 0;
try {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) {
clsValue += entry.value;
this.metrics.cls = Math.round(clsValue * 1000) / 1000;
// Mark shifting elements (limit to first 5)
if (this.settings.performance && entry.sources && entry.sources.length > 0) {
const source = entry.sources[0];
if (source.node && !this.processedElements.has(source.node)) {
this.markCLSElement(source.node, entry.value);
}
}
this.updateHUDMetric('cls', this.metrics.cls.toFixed(3));
}
}
});
observer.observe({ type: 'layout-shift', buffered: true });
} catch (e) {
console.log('CLS observation not supported');
}
}
runInitialAnalysis() {
// Run lighter analysis initially
if (this.settings.images && this.enabled) {
this.analyzeVisibleImages();
}
}
analyzeVisibleImages() {
if (!this.enabled) return;
const images = document.querySelectorAll('img');
let analyzed = 0;
const maxAnalyze = 20; // Limit initial analysis
images.forEach(img => {
if (analyzed >= maxAnalyze) return;
if (this.processedElements.has(img)) return;
if (!this.isElementVisible(img)) return;
analyzed++;
const analyze = () => {
const naturalWidth = img.naturalWidth;
const naturalHeight = img.naturalHeight;
const displayedWidth = img.clientWidth;
const displayedHeight = img.clientHeight;
if (!naturalWidth || !displayedWidth) return;
let issueFound = false;
let issueType = '';
let details = '';
// Check oversized
if (naturalWidth > displayedWidth * 1.2) {
img.style.border = '3px solid #f44336';
issueFound = true;
issueType = 'oversized';
const percentage = Math.round(((naturalWidth - displayedWidth) / naturalWidth) * 100);
details = `Natural: ${naturalWidth}×${naturalHeight}<br>Displayed: ${displayedWidth}×${displayedHeight}<br>🔴 ${percentage}% oversized`;
const issue = {
type: 'image-size',
element: img,
title: 'Oversized Image',
impact: `${percentage}% waste`,
details: `${naturalWidth}×${naturalHeight} → ${displayedWidth}×${displayedHeight}`
};
this.issues.push(issue);
this.issuesByType.oversized.push(issue);
}
// Check missing dimensions
if (!img.getAttribute('width') || !img.getAttribute('height')) {
if (!issueFound) {
img.style.border = '3px solid #ffeb3b';
issueType = 'cls-risk';
details = '⚠️ Missing width/height<br>Can cause layout shift';
}
const clsIssue = {
type: 'cls',
element: img,
title: 'Missing Dimensions',
impact: 'CLS risk',
details: 'No width/height attributes'
};
this.issues.push(clsIssue);
this.issuesByType.cls.push(clsIssue);
}
// Add overlay with details
if (issueFound && details) {
this.addImageOverlay(img, details, issueType);
}
this.processedElements.add(img);
};
if (img.complete) {
analyze();
} else {
img.addEventListener('load', analyze, { once: true });
}
});
this.updateIssueCount();
}
addImageOverlay(img, content, type) {
// Check if parent can hold overlay
let container = img.parentElement;
if (!container) return;
// Make container positionable
const position = window.getComputedStyle(container).position;
if (position === 'static') {
container.style.position = 'relative';
}
// Remove any existing overlay
const existingOverlay = container.querySelector('.bp-image-overlay');
if (existingOverlay) {
existingOverlay.remove();
}
// Create overlay
const overlay = document.createElement('div');
overlay.className = 'bp-image-overlay';
overlay.innerHTML = content;
overlay.style.cssText = `
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: ${type === 'oversized' ? 'rgba(244, 67, 54, 0.95)' : 'rgba(255, 235, 59, 0.95)'};
color: ${type === 'oversized' ? 'white' : 'black'};
padding: 8px;
font-size: 11px;
font-family: -apple-system, sans-serif;
line-height: 1.4;
z-index: 10000;
pointer-events: none;
display: ${this.overlaysVisible ? 'block' : 'none'};
`;
try {
container.appendChild(overlay);
} catch (e) {
console.log('Could not add overlay');
}
}
markLCPElement(element) {
if (!this.enabled) return;
element.style.border = '4px dashed #9c27b0';
// Determine LCP quality
const lcpTime = this.metrics.lcp;
const quality = lcpTime <= 2500 ? 'Good' : lcpTime <= 4000 ? 'Needs Work' : 'Poor';
const color = lcpTime <= 2500 ? '#4caf50' : lcpTime <= 4000 ? '#ff9800' : '#f44336';
// Add LCP badge
const badge = document.createElement('div');
badge.className = 'bp-lcp-badge';
badge.innerHTML = `
<div style="font-weight: bold;">LCP: ${(lcpTime/1000).toFixed(1)}s</div>
<div style="font-size: 10px; margin-top: 2px; color: ${color};">${quality}</div>
`;
badge.style.cssText = `
position: absolute;
top: 5px;
left: 5px;
background: #9c27b0;
color: white;
padding: 6px 10px;
border-radius: 4px;
font-size: 12px;
z-index: 10001;
font-family: -apple-system, sans-serif;
cursor: pointer;
`;
// Add click handler for recommendations
badge.addEventListener('click', () => {
let tips = 'LCP Optimization Tips:\n\n';
if (element.tagName === 'IMG') {
if (element.loading === 'lazy') {
tips += '❌ Remove loading="lazy" from LCP image\n';
}
tips += '✅ Add fetchpriority="high"\n';
tips += '✅ Use modern formats (WebP/AVIF)\n';
tips += '✅ Optimize image size\n';
} else {
tips += '✅ Preload critical fonts\n';
tips += '✅ Inline critical CSS\n';
tips += '✅ Reduce server response time\n';
}
this.showToast(tips);
});
// Make element positionable
if (window.getComputedStyle(element).position === 'static') {
element.style.position = 'relative';
}
try {
element.appendChild(badge);
// Track this LCP element
this.lcpElements.push({ element, badge });
} catch (e) {
// If can't append to element, try parent
if (element.parentElement) {
element.parentElement.style.position = 'relative';
element.parentElement.appendChild(badge);
this.lcpElements.push({ element, badge });
}
}
}
markCLSElement(element, shift) {
if (!element || this.processedElements.has(element)) return;
element.style.outline = '2px dashed #ff9800';
// Add CLS indicator
const indicator = document.createElement('div');
indicator.className = 'bp-cls-indicator';
indicator.textContent = `CLS: ${shift.toFixed(3)}`;
indicator.style.cssText = `
position: absolute;
top: -20px;
left: 0;
background: #ff9800;
color: white;
padding: 2px 6px;
border-radius: 3px;
font-size: 10px;
z-index: 10001;
font-family: -apple-system, sans-serif;
`;
if (window.getComputedStyle(element).position === 'static') {
element.style.position = 'relative';
}
try {
element.appendChild(indicator);
} catch (e) {
// Silent fail
}
this.processedElements.add(element);
}
createHUD() {
// Remove any existing HUD
const existingHUD = document.querySelector('.bp-hud');
if (existingHUD) existingHUD.remove();
const hud = document.createElement('div');
hud.className = 'bp-hud';
hud.style.cssText = `
position: fixed;
top: 10px;
right: 10px;
background: rgba(33, 33, 33, 0.95);
color: white;
padding: 12px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.3);
font-family: -apple-system, sans-serif;
font-size: 12px;
z-index: 2147483645;
min-width: 200px;
backdrop-filter: blur(10px);
`;
hud.innerHTML = `
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<strong style="font-size: 14px;">🚀 Bad Page</strong>
<div>
<button id="bp-power" style="background: ${this.enabled ? '#4caf50' : '#f44336'}; border: none; color: white; cursor: pointer; padding: 4px 8px; border-radius: 4px; margin-right: 4px;" title="${this.enabled ? 'Turn Off' : 'Turn On'}">⚡</button>
<button id="bp-toggle-overlays" style="background: ${this.overlaysVisible ? '#2196f3' : 'rgba(255,255,255,0.1)'}; border: none; color: white; cursor: pointer; padding: 4px 8px; border-radius: 4px; margin-right: 4px;" title="Toggle Overlays">${this.overlaysVisible ? '👁' : '👁🗨'}</button>
<button id="bp-minimize" style="background: none; border: none; color: white; cursor: pointer; padding: 4px;">_</button>
</div>
</div>
<div class="bp-hud-content">
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">
<div style="background: rgba(255,255,255,0.1); padding: 6px; border-radius: 4px; cursor: help;" title="Largest Contentful Paint - when the main content loads">
<div style="font-size: 10px; opacity: 0.7;">LCP</div>
<div id="bp-metric-lcp" style="font-weight: bold; color: #ffeb3b;">—</div>
</div>
<div style="background: rgba(255,255,255,0.1); padding: 6px; border-radius: 4px; cursor: help;" title="First Contentful Paint - when first content appears">
<div style="font-size: 10px; opacity: 0.7;">FCP</div>
<div id="bp-metric-fcp" style="font-weight: bold; color: #ffeb3b;">—</div>
</div>
<div style="background: rgba(255,255,255,0.1); padding: 6px; border-radius: 4px; cursor: help;" title="Cumulative Layout Shift - visual stability score">
<div style="font-size: 10px; opacity: 0.7;">CLS</div>
<div id="bp-metric-cls" style="font-weight: bold; color: #ffeb3b;">0</div>
</div>
<div style="background: rgba(255,255,255,0.1); padding: 6px; border-radius: 4px; cursor: help;" title="Total performance issues found">
<div style="font-size: 10px; opacity: 0.7;">Issues</div>
<div id="bp-issue-count" style="font-weight: bold; color: #ff9800;">0</div>
</div>
</div>
<div id="bp-issue-details" style="background: rgba(255,255,255,0.05); padding: 8px; border-radius: 4px; font-size: 11px; line-height: 1.4; max-height: 150px; overflow-y: auto; display: none;">
<!-- Issue details will appear here -->
</div>
<div style="margin-top: 10px;">
<button id="bp-reanalyze" style="width: 100%; padding: 6px; background: #2196f3; border: none; color: white; border-radius: 4px; cursor: pointer; font-size: 12px; margin-bottom: 8px;">Re-analyze Page</button>
<label style="display: flex; align-items: center; gap: 4px; cursor: pointer;">
<input type="checkbox" id="bp-toggle-images" checked>
<span style="font-size: 11px;">Analyze Images</span>
</label>
</div>
</div>
`;
document.body.appendChild(hud);
this.hud = hud;
}
updateHUDMetric(metric, value) {
const element = document.getElementById(`bp-metric-${metric}`);
if (element) {
element.textContent = value;
}
}
updateIssueCount() {
const countElement = document.getElementById('bp-issue-count');
const detailsElement = document.getElementById('bp-issue-details');
if (countElement) {
countElement.textContent = this.issues.length;
// Show issue details if there are issues
if (this.issues.length > 0 && detailsElement) {
let detailsHTML = '<div style="margin-bottom: 4px; font-weight: bold; color: #ff9800;">Issues Found:</div>';
// Group issues by type
if (this.issuesByType.oversized.length > 0) {
detailsHTML += `<div style="margin-bottom: 4px;">🔴 <strong>${this.issuesByType.oversized.length} Oversized Images</strong></div>`;
this.issuesByType.oversized.slice(0, 3).forEach(issue => {
detailsHTML += `<div style="margin-left: 16px; opacity: 0.8; font-size: 10px;">• ${issue.details}</div>`;
});
}
if (this.issuesByType.cls.length > 0) {
detailsHTML += `<div style="margin-bottom: 4px;">🟡 <strong>${this.issuesByType.cls.length} CLS Risks</strong></div>`;
detailsHTML += `<div style="margin-left: 16px; opacity: 0.8; font-size: 10px;">• Images missing width/height</div>`;
}
detailsElement.innerHTML = detailsHTML;
detailsElement.style.display = 'block';
} else if (detailsElement) {
detailsElement.style.display = 'none';
}
}
}
setupListeners() {
// Power button - master on/off
document.getElementById('bp-power')?.addEventListener('click', () => {
this.toggleEnabled();
});
// HUD controls
document.getElementById('bp-toggle-overlays')?.addEventListener('click', () => {
this.toggleOverlays();
});
document.getElementById('bp-minimize')?.addEventListener('click', () => {
this.toggleHUD();
});
document.getElementById('bp-toggle-images')?.addEventListener('change', (e) => {
this.settings.images = e.target.checked;
if (e.target.checked && this.enabled) {
this.analyzeVisibleImages();
}
});
// Re-analyze button
document.getElementById('bp-reanalyze')?.addEventListener('click', () => {
const btn = document.getElementById('bp-reanalyze');
if (btn) {
btn.disabled = true;
btn.textContent = 'Analyzing...';
// Clear and re-analyze
this.cleanupVisuals();
this.issues = [];
this.issuesByType = {
oversized: [],
cls: [],
format: [],
lazy: []
};
this.processedElements = new WeakSet();
setTimeout(() => {
this.runInitialAnalysis();
this.collectMetrics();
btn.disabled = false;
btn.textContent = 'Re-analyze Page';
this.showToast(`Analysis complete: ${this.issues.length} issues found`);
}, 500);
}
});
// Show/hide issue details on hover
const issueMetric = document.querySelector('[title="Total performance issues found"]');
if (issueMetric) {
issueMetric.addEventListener('mouseenter', () => {
const details = document.getElementById('bp-issue-details');
if (details && this.issues.length > 0) {
details.style.display = 'block';
}
});
issueMetric.addEventListener('mouseleave', () => {
setTimeout(() => {
const details = document.getElementById('bp-issue-details');
if (details && !details.matches(':hover')) {
details.style.display = 'none';
}
}, 300);
});
}
// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
switch(request.action) {
case 'getStatus':
sendResponse({
issueCount: this.issues.length,
performanceScore: this.metrics.lcp ? this.calculatePerformanceScore() : null
});
break;
case 'analyze':
this.runInitialAnalysis();
break;
case 'toggleOverlays':
this.toggleOverlays();
break;
case 'export':
this.exportReport();
break;
}
return true;
});
}
setupLazyObserver() {
// Use IntersectionObserver for lazy analysis
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && !this.processedElements.has(entry.target)) {
this.analyzeElement(entry.target);
}
});
}, {
rootMargin: '50px'
});
// Observe images that aren't processed yet
setTimeout(() => {
document.querySelectorAll('img').forEach(img => {
if (!this.processedElements.has(img)) {
observer.observe(img);
}
});
}, 2000);
}
analyzeElement(element) {
if (element.tagName === 'IMG' && this.settings.images) {
// Same analysis as before but for individual element
const naturalWidth = element.naturalWidth;
const displayedWidth = element.clientWidth;
if (naturalWidth && displayedWidth && naturalWidth > displayedWidth * 1.2) {
element.style.border = '3px solid #f44336';
const percentage = Math.round(((naturalWidth - displayedWidth) / naturalWidth) * 100);
const details = `Natural: ${naturalWidth}px<br>Displayed: ${displayedWidth}px<br>🔴 ${percentage}% oversized`;
this.addImageOverlay(element, details, 'oversized');
}
this.processedElements.add(element);
}
}
toggleOverlays() {
this.overlaysVisible = !this.overlaysVisible;
// Update button visual state
const btn = document.getElementById('bp-toggle-overlays');
if (btn) {
btn.style.background = this.overlaysVisible ? '#2196f3' : 'rgba(255,255,255,0.1)';
btn.innerHTML = this.overlaysVisible ? '👁' : '👁🗨';
}
// Toggle all overlays
document.querySelectorAll('.bp-image-overlay').forEach(overlay => {
overlay.style.display = this.overlaysVisible ? 'block' : 'none';
});
document.querySelectorAll('.bp-lcp-badge, .bp-cls-indicator').forEach(badge => {
badge.style.display = this.overlaysVisible ? 'block' : 'none';
});
// Show toast notification
this.showToast(this.overlaysVisible ? 'Overlays visible' : 'Overlays hidden');
}
toggleHUD() {
this.hudMinimized = !this.hudMinimized;
const content = this.hud.querySelector('.bp-hud-content');
if (content) {
content.style.display = this.hudMinimized ? 'none' : 'block';
}
}
toggleEnabled() {
this.enabled = !this.enabled;
const powerBtn = document.getElementById('bp-power');
if (powerBtn) {
powerBtn.style.background = this.enabled ? '#4caf50' : '#f44336';
}
if (!this.enabled) {
// Clean up all visual indicators
this.cleanupVisuals();
} else {
// Re-run analysis
this.runInitialAnalysis();
this.collectMetrics();
}
}
showToast(message) {
// Remove existing toast
const existingToast = document.querySelector('.bp-toast');
if (existingToast) existingToast.remove();
const toast = document.createElement('div');
toast.className = 'bp-toast';
toast.style.cssText = `
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: rgba(33, 33, 33, 0.95);
color: white;
padding: 10px 20px;
border-radius: 6px;
font-family: -apple-system, sans-serif;
font-size: 13px;
z-index: 2147483647;
animation: slideUp 0.3s ease;
max-width: 400px;
white-space: pre-wrap;
line-height: 1.4;
`;
toast.textContent = message;
document.body.appendChild(toast);
// Longer display for multi-line messages
const displayTime = message.includes('\n') ? 4000 : 2000;
setTimeout(() => {
toast.style.animation = 'slideDown 0.3s ease';
setTimeout(() => toast.remove(), 300);
}, displayTime);
}
cleanupVisuals() {
// Remove all borders
document.querySelectorAll('img').forEach(img => {
img.style.border = '';
});
// Remove all overlays
document.querySelectorAll('.bp-image-overlay').forEach(overlay => {
overlay.remove();
});
// Remove LCP markers
this.lcpElements.forEach(el => {
if (el.badge) el.badge.remove();
if (el.element) el.element.style.border = '';
});
this.lcpElements = [];
// Remove CLS indicators
document.querySelectorAll('.bp-cls-indicator').forEach(indicator => {
indicator.remove();
});
document.querySelectorAll('[style*="outline"]').forEach(el => {
el.style.outline = '';
});
// Clear issues
this.issues = [];
this.issuesByType = {
oversized: [],
cls: [],
format: [],
lazy: []
};
this.updateIssueCount();
// Clear processed elements
this.processedElements = new WeakSet();
}
calculatePerformanceScore() {
let score = 100;
// Deduct points based on metrics
if (this.metrics.lcp > 4000) score -= 30;
else if (this.metrics.lcp > 2500) score -= 15;
if (this.metrics.fcp > 3000) score -= 20;
else if (this.metrics.fcp > 1800) score -= 10;
if (this.metrics.cls > 0.25) score -= 20;
else if (this.metrics.cls > 0.1) score -= 10;
// Deduct for issues
score -= this.issues.length * 2;
return Math.max(0, Math.min(100, score));
}
exportReport() {
const report = {
url: window.location.href,
timestamp: new Date().toISOString(),
metrics: this.metrics,
issues: this.issues.map(i => ({
type: i.type,
title: i.title,
impact: i.impact
}))
};
const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `bad-page-report-${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
}
isElementVisible(element) {
const rect = element.getBoundingClientRect();
return (
rect.top < window.innerHeight &&
rect.bottom > 0 &&
rect.left < window.innerWidth &&
rect.right > 0
);
}
}
// Initialize when DOM is ready, with delay to not block page load
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
window.badPage = new BadPageAnalyzer();
}, 1000);
});
} else {
setTimeout(() => {
window.badPage = new BadPageAnalyzer();
}, 1000);
}
// Add animation styles
const style = document.createElement('style');
style.textContent = `
@keyframes slideUp {
from { opacity: 0; transform: translateX(-50%) translateY(20px); }
to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
@keyframes slideDown {
from { opacity: 1; transform: translateX(-50%) translateY(0); }
to { opacity: 0; transform: translateX(-50%) translateY(20px); }
}
`;
document.head.appendChild(style);