-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
604 lines (493 loc) · 18.5 KB
/
Copy pathscript.js
File metadata and controls
604 lines (493 loc) · 18.5 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
document.addEventListener("DOMContentLoaded", () => {
// パフォーマンス測定
let startTime = performance.now();
// CLS測定用
let clsValue = 0;
let lastLayoutShiftScore = 0;
// CLSを観察する
if ("LayoutShiftAttribution" in window) {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) {
clsValue += entry.value;
lastLayoutShiftScore = entry.value;
}
}
// CLSの値を表示
const clsElement = document.getElementById("cls-value");
if (clsElement) {
clsElement.textContent = clsValue.toFixed(3);
}
});
observer.observe({ type: "layout-shift", buffered: true });
}
// ページ読み込み時間の表示
window.addEventListener("load", () => {
const loadTime = (performance.now() - startTime).toFixed(0);
const loadTimeElement = document.getElementById("load-time");
if (loadTimeElement) {
loadTimeElement.textContent = `${loadTime}ms`;
}
});
// ファーストビューのデモ
setupFirstViewDemo();
// アルゴリズムと要素計算のデモ
setupAlgorithmDemo();
// スクロール領域のデモ
setupScrollAreaDemo();
// コンテンツ読み込みのデモ
setupContentLoadingDemo();
// スクロール検知のデモ
setupScrollDetectionDemo();
// タブ切り替え機能
setupTabs();
});
// ファーストビューのデモセットアップ
function setupFirstViewDemo() {
// プレースホルダーの適切な高さ設定(CLS防止)
const placeholders = document.querySelectorAll(".placeholder");
placeholders.forEach((placeholder) => {
const height = placeholder.getAttribute("data-height");
if (height) {
placeholder.style.height = height;
}
});
}
// アルゴリズムと要素計算のデモセットアップ
function setupAlgorithmDemo() {
const elementContainer = document.getElementById("element-container");
const elementCountInput = document.getElementById("element-count");
const elementCountValue = document.getElementById("element-count-value");
const checkVisibilityBtn = document.getElementById("check-visibility");
const visibleCountElement = document.getElementById("visible-count");
const calcTimeElement = document.getElementById("calc-time");
if (
!elementContainer ||
!elementCountInput ||
!elementCountValue ||
!checkVisibilityBtn
)
return;
// 要素数スライダーの更新
elementCountInput.addEventListener("input", () => {
const count = elementCountInput.value;
elementCountValue.textContent = count;
generateElements(count);
});
// 可視要素チェックボタン
checkVisibilityBtn.addEventListener("click", () => {
const startTime = performance.now();
// 1. 単純なループ(非効率)
const visibleElements = checkVisibleElements();
const endTime = performance.now();
const calcTime = (endTime - startTime).toFixed(2);
visibleCountElement.textContent = visibleElements.length;
calcTimeElement.textContent = `${calcTime}ms`;
// 可視要素のハイライト
document.querySelectorAll(".element-item").forEach((el) => {
el.classList.remove("visible");
});
visibleElements.forEach((el) => {
el.classList.add("visible");
});
});
// 初期要素の生成
generateElements(elementCountInput.value);
// 要素を生成する関数
function generateElements(count) {
elementContainer.innerHTML = "";
for (let i = 0; i < count; i++) {
const el = document.createElement("div");
el.className = "element-item";
el.textContent = `要素 ${i + 1}`;
el.dataset.id = i + 1;
elementContainer.appendChild(el);
}
}
// 可視要素をチェックする関数(単純なループ)
function checkVisibleElements() {
const elements = elementContainer.querySelectorAll(".element-item");
const containerRect = elementContainer.getBoundingClientRect();
const visibleElements = [];
elements.forEach((element) => {
const elementRect = element.getBoundingClientRect();
// 要素が表示領域内にあるかどうかを確認
if (
elementRect.top < containerRect.bottom &&
elementRect.bottom > containerRect.top
) {
visibleElements.push(element);
}
});
return visibleElements;
}
}
// スクロール領域のデモセットアップ
function setupScrollAreaDemo() {
const badScrollContainer = document.querySelector(".bad-scroll");
const goodScrollContainer = document.querySelector(".good-scroll");
if (!badScrollContainer || !goodScrollContainer) return;
// 問題のあるスクロール(CLS発生)
function loadBadExample() {
for (let i = 0; i < 20; i++) {
const delay = Math.random() * 1000;
setTimeout(() => {
const item = document.createElement("div");
item.className = "content-item";
// ランダムなコンテンツの高さ(これがCLSの原因になる)
const textLength = Math.floor(Math.random() * 200) + 20;
item.textContent = "".padStart(textLength, "あ");
badScrollContainer.appendChild(item);
}, delay);
}
}
// 最適化されたスクロール(CLS防止)
function loadGoodExample() {
// 先にプレースホルダーを配置(高さ確保)
for (let i = 0; i < 20; i++) {
const item = document.createElement("div");
item.className = "content-item";
item.style.minHeight = "100px";
item.innerHTML = '<div class="placeholder">読み込み中...</div>';
goodScrollContainer.appendChild(item);
}
// 実際のコンテンツをロード
const items = goodScrollContainer.querySelectorAll(".content-item");
items.forEach((item, index) => {
const delay = Math.random() * 1000;
setTimeout(() => {
const textLength = Math.floor(Math.random() * 200) + 20;
item.innerHTML = "".padStart(textLength, "あ");
}, delay);
});
}
// タブ切り替え時にコンテンツをロード
const badTab = document.querySelector('[data-tab="bad"]');
const goodTab = document.querySelector('[data-tab="good"]');
badTab.addEventListener("click", () => {
if (badScrollContainer.children.length === 0) {
loadBadExample();
}
});
goodTab.addEventListener("click", () => {
if (goodScrollContainer.children.length === 0) {
loadGoodExample();
}
});
// 初期表示(悪い例)
loadBadExample();
}
// コンテンツ読み込みのデモセットアップ
function setupContentLoadingDemo() {
const lazyContainer = document.getElementById("lazy-loading-container");
const infiniteContainer = document.getElementById(
"infinite-scroll-container"
);
const virtualContainer = document.getElementById("virtual-scroll-container");
if (!lazyContainer || !infiniteContainer || !virtualContainer) return;
// 遅延読み込みのデモ
setupLazyLoading(lazyContainer);
// 無限スクロールのデモ
setupInfiniteScroll(infiniteContainer);
// 仮想スクロールのデモ
setupVirtualScroll(virtualContainer);
}
// 遅延読み込みのデモ
function setupLazyLoading(container) {
// 画像URLの配列(プレースホルダー画像)
const imageUrls = [
"https://via.placeholder.com/400x200?text=画像1",
"https://via.placeholder.com/400x200?text=画像2",
"https://via.placeholder.com/400x200?text=画像3",
"https://via.placeholder.com/400x200?text=画像4",
"https://via.placeholder.com/400x200?text=画像5",
"https://via.placeholder.com/400x200?text=画像6",
"https://via.placeholder.com/400x200?text=画像7",
"https://via.placeholder.com/400x200?text=画像8",
"https://via.placeholder.com/400x200?text=画像9",
"https://via.placeholder.com/400x200?text=画像10",
];
// コンテナにプレースホルダーアイテムを追加
imageUrls.forEach((url, index) => {
const item = document.createElement("div");
item.className = "lazy-item loading";
item.innerHTML = `<div class="placeholder">画像 ${
index + 1
} 読み込み中...</div>`;
container.appendChild(item);
});
// Intersection Observerを使用して遅延読み込み
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const item = entry.target;
const index = Array.from(container.children).indexOf(item);
if (index >= 0 && index < imageUrls.length) {
// 画像を読み込む
setTimeout(() => {
const img = document.createElement("img");
img.src = imageUrls[index];
img.alt = `画像 ${index + 1}`;
img.style.opacity = "0";
img.onload = () => {
item.innerHTML = "";
item.appendChild(img);
item.classList.remove("loading");
// フェードイン
setTimeout(() => {
img.style.opacity = "1";
}, 50);
};
}, Math.random() * 1000 + 500); // ランダムな遅延
}
// 一度読み込んだら監視を解除
observer.unobserve(item);
}
});
},
{
root: container,
threshold: 0.1,
}
);
// すべての遅延読み込みアイテムを監視
document.querySelectorAll(".lazy-item").forEach((item) => {
observer.observe(item);
});
}
// 無限スクロールのデモ
function setupInfiniteScroll(container) {
let page = 1;
let loading = false;
const itemsPerPage = 10;
// 初期アイテムを読み込む
loadItems();
// スクロールイベントリスナー
container.addEventListener("scroll", () => {
if (loading) return;
// スクロール位置がコンテナの下部に近づいたら新しいアイテムを読み込む
const scrollTop = container.scrollTop;
const scrollHeight = container.scrollHeight;
const clientHeight = container.clientHeight;
if (scrollTop + clientHeight >= scrollHeight - 100) {
loadItems();
}
});
// アイテムを読み込む関数
function loadItems() {
loading = true;
// ローディングインジケータを追加
const loadingIndicator = document.createElement("div");
loadingIndicator.className = "loading-indicator";
loadingIndicator.textContent = "読み込み中...";
container.appendChild(loadingIndicator);
// アイテム読み込みを遅延させる(APIリクエストのシミュレーション)
setTimeout(() => {
// ローディングインジケータを削除
container.removeChild(loadingIndicator);
// 新しいアイテムを追加
for (let i = 0; i < itemsPerPage; i++) {
const itemIndex = (page - 1) * itemsPerPage + i + 1;
const item = document.createElement("div");
item.className = "infinite-item";
item.textContent = `アイテム ${itemIndex}`;
container.appendChild(item);
}
page++;
loading = false;
}, 1000);
}
}
// 仮想スクロールのデモ
function setupVirtualScroll(container) {
const totalItems = 10000; // 膨大な数のアイテム
const itemHeight = 50; // アイテムの高さ
const visibleItems = 20; // 画面に表示するアイテム数
// 仮想スクロールのコンテナを作成
const viewport = document.createElement("div");
viewport.className = "virtual-viewport";
container.appendChild(viewport);
// 実際のコンテンツを表示する要素
const content = document.createElement("div");
content.className = "virtual-content";
viewport.appendChild(content);
// スクロール全体の高さを設定(すべてのアイテムが存在するかのように)
const totalHeight = totalItems * itemHeight;
content.style.height = `${totalHeight}px`;
// 表示すべきアイテムを更新する関数
function updateVisibleItems() {
const scrollTop = viewport.scrollTop;
const startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = Math.min(startIndex + visibleItems, totalItems - 1);
// 現在のアイテムをクリア
content.innerHTML = "";
// 表示範囲のアイテムのみをレンダリング
for (let i = startIndex; i <= endIndex; i++) {
const item = document.createElement("div");
item.className = "virtual-item";
item.textContent = `アイテム ${i + 1} / ${totalItems}`;
item.style.position = "absolute";
item.style.top = `${i * itemHeight}px`;
item.style.width = "100%";
content.appendChild(item);
}
}
// スクロールイベントで表示アイテムを更新
viewport.addEventListener("scroll", () => {
updateVisibleItems();
});
// 初期表示
updateVisibleItems();
}
// スクロール検知のデモセットアップ
function setupScrollDetectionDemo() {
setupScrollEvent();
setupScrollThrottle();
setupScrollObserver();
}
// 通常のスクロールイベント
function setupScrollEvent() {
const scrollArea = document.getElementById("scroll-event-area");
const eventCountElement = document.getElementById("event-count");
const eventCpuElement = document.getElementById("event-cpu");
if (!scrollArea || !eventCountElement || !eventCpuElement) return;
// テスト要素の生成
generateTestItems(scrollArea, 100);
let eventCount = 0;
// スクロールイベントリスナー(最適化なし)
scrollArea.addEventListener("scroll", () => {
eventCount++;
eventCountElement.textContent = eventCount;
// CPU使用率のシミュレーション
const startTime = performance.now();
// 重い処理のシミュレーション
checkElementsVisibility(scrollArea);
const endTime = performance.now();
eventCpuElement.textContent = `${(endTime - startTime).toFixed(2)}ms`;
});
}
// スロットリングを使用したスクロールイベント
function setupScrollThrottle() {
const scrollArea = document.getElementById("scroll-throttle-area");
const throttleCountElement = document.getElementById("throttle-count");
const throttleCpuElement = document.getElementById("throttle-cpu");
if (!scrollArea || !throttleCountElement || !throttleCpuElement) return;
// テスト要素の生成
generateTestItems(scrollArea, 100);
let eventCount = 0;
// スロットリング関数
function throttle(callback, delay) {
let lastCall = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
return callback(...args);
};
}
// スロットリングされたスクロールハンドラ
const throttledScroll = throttle(() => {
eventCount++;
throttleCountElement.textContent = eventCount;
// CPU使用率のシミュレーション
const startTime = performance.now();
// 重い処理のシミュレーション
checkElementsVisibility(scrollArea);
const endTime = performance.now();
throttleCpuElement.textContent = `${(endTime - startTime).toFixed(2)}ms`;
}, 200); // 200msごとに実行
// スクロールイベントリスナー(スロットリング適用)
scrollArea.addEventListener("scroll", throttledScroll);
}
// IntersectionObserverを使用したスクロール検知
function setupScrollObserver() {
const scrollArea = document.getElementById("scroll-observer-area");
const observerCountElement = document.getElementById("observer-count");
const observerCpuElement = document.getElementById("observer-cpu");
if (!scrollArea || !observerCountElement || !observerCpuElement) return;
// テスト要素の生成
generateTestItems(scrollArea, 100);
let callbackCount = 0;
// Intersection Observerのコールバック
const observerCallback = (entries, observer) => {
callbackCount++;
observerCountElement.textContent = callbackCount;
const startTime = performance.now();
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add("visible");
} else {
entry.target.classList.remove("visible");
}
});
const endTime = performance.now();
observerCpuElement.textContent = `${(endTime - startTime).toFixed(2)}ms`;
};
// Intersection Observerのセットアップ
const observer = new IntersectionObserver(observerCallback, {
root: scrollArea,
threshold: 0.1,
});
// すべてのテスト要素を監視
const testItems = scrollArea.querySelectorAll(".test-item");
testItems.forEach((item) => {
observer.observe(item);
});
}
// テスト要素を生成する関数
function generateTestItems(container, count) {
for (let i = 0; i < count; i++) {
const item = document.createElement("div");
item.className = "test-item";
item.textContent = `テスト要素 ${i + 1}`;
container.appendChild(item);
}
}
// 要素の可視性をチェックする関数(重い処理のシミュレーション)
function checkElementsVisibility(container) {
const elements = container.querySelectorAll(".test-item");
const containerRect = container.getBoundingClientRect();
elements.forEach((element) => {
const elementRect = element.getBoundingClientRect();
if (
elementRect.top < containerRect.bottom &&
elementRect.bottom > containerRect.top
) {
element.classList.add("visible");
} else {
element.classList.remove("visible");
}
});
// 人工的な遅延を追加(CPUの負荷をシミュレート)
const start = performance.now();
while (performance.now() - start < 5) {
// ビジーウェイト
}
}
// タブ切り替え機能のセットアップ
function setupTabs() {
const tabButtons = document.querySelectorAll(".tab-btn");
tabButtons.forEach((button) => {
button.addEventListener("click", () => {
const tabGroup = button.closest(".tabs").parentElement;
const tabTarget = button.getAttribute("data-tab");
// 同じグループのタブをすべて非アクティブにする
tabGroup.querySelectorAll(".tab-btn").forEach((btn) => {
btn.classList.remove("active");
});
// 選択されたタブをアクティブにする
button.classList.add("active");
// タブコンテンツを切り替える
tabGroup.querySelectorAll(".tab-content").forEach((content) => {
content.classList.remove("active");
});
const targetContent = tabGroup.querySelector(`#${tabTarget}-tab`);
if (targetContent) {
targetContent.classList.add("active");
}
});
});
}