page-load-metrics 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.ko.md +161 -0
- package/README.md +162 -2
- package/cli.mjs +316 -0
- package/package.json +38 -4
- package/page_load_metrics.js +180 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 El Fenomeno
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.ko.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
<img src="https://raw.githubusercontent.com/elfenomenokim/page-load-metrics/main/docs/logo.svg" width="96" height="96" alt="페이지 위의 계기판">
|
|
4
|
+
|
|
5
|
+
# page-load-metrics
|
|
6
|
+
|
|
7
|
+
페이지 로딩 속도를 차가운 상태로 세 번 재고, 지난번보다 무엇이 달라졌는지 보여 줍니다.
|
|
8
|
+
|
|
9
|
+
[English](README.md) · Node 22 이상 · Chrome · 의존성 없음
|
|
10
|
+
|
|
11
|
+
[](https://github.com/elfenomenokim/page-load-metrics/actions/workflows/tests.yml)
|
|
12
|
+
[](https://www.npmjs.com/package/page-load-metrics)
|
|
13
|
+
[](LICENSE)
|
|
14
|
+
|
|
15
|
+
[설치](#설치) · [빠르게 써 보기](#빠르게-써-보기) · [로그인한 페이지](#로그인한-페이지) · [참고](#참고) · [한계](#한계)
|
|
16
|
+
|
|
17
|
+
</div>
|
|
18
|
+
|
|
19
|
+
```console
|
|
20
|
+
$ npx page-load-metrics https://example.com
|
|
21
|
+
https://example.com · median of 3 cold loads · 1350x940
|
|
22
|
+
|
|
23
|
+
metric median rating change runs
|
|
24
|
+
------------------ ------ ------ -------------- ----
|
|
25
|
+
ttfb 117 ms good -8 ms (-6%) 3/3
|
|
26
|
+
fcp 188 ms good -52 ms (-22%) 3/3
|
|
27
|
+
lcp 236 ms good -116 ms (-33%) 3/3
|
|
28
|
+
cls 0 good 0 3/3
|
|
29
|
+
blocking 0 ms good 0 ms 3/3
|
|
30
|
+
dom_content_loaded 163 ms -11 ms (-6%) 3/3
|
|
31
|
+
load 164 ms -11 ms (-6%) 3/3
|
|
32
|
+
transfer 1.6 kB 0 kB (0%) 3/3
|
|
33
|
+
requests 1 0 (0%) 3/3
|
|
34
|
+
|
|
35
|
+
LCP element: p "Данный домен предназначен для "
|
|
36
|
+
change: against 2026-11-21T03:55:58.056Z
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
<sub>2026-11-21 맥 미니에서 두 번 잰 것 중 두 번째 실행입니다. `change`는 첫 번째와 비교한 값입니다. example.com이 이 기기에 러시아어 문구를 보내서 LCP 문단이 러시아어로 나왔습니다.</sub>
|
|
40
|
+
|
|
41
|
+
## 필요한 이유
|
|
42
|
+
|
|
43
|
+
페이지를 고친 뒤 느려졌는지 알고 싶을 때가 있습니다. Lighthouse는 전체 감사와 점수로 답하고,
|
|
44
|
+
[web-vitals](https://github.com/GoogleChrome/web-vitals)는 페이지에 심어 배포한 뒤 실제 방문자
|
|
45
|
+
기록으로 답합니다. page-load-metrics는 "느려졌나?"라는 좁은 질문에 몇 초 만에 답합니다.
|
|
46
|
+
|
|
47
|
+
- **매번 차가운 상태.** 실행마다 새 브라우저 공간을 써서 캐시·쿠키·서비스 워커가 남지 않습니다.
|
|
48
|
+
세 번의 중앙값이라 한 번 튀는 값에 흔들리지 않습니다.
|
|
49
|
+
- **지난번과 비교.** 결과를 주소와 화면 크기별로 저장하고, 다음 실행에서 차이를 보여 줍니다.
|
|
50
|
+
배포 전후에 한 번씩 돌리면 됩니다.
|
|
51
|
+
- **모르는 값은 모름.** 브라우저가 알려 주지 못한 지표는 `n/a`로 나옵니다. 안심되는 0으로
|
|
52
|
+
바꾸지 않습니다.
|
|
53
|
+
- **점수가 아니라 원인.** LCP 요소와 그 로딩·그리기 시간, 흔들린 요소, 메인 스레드를 막은
|
|
54
|
+
스크립트, 가장 무거운 파일까지 보여 줍니다.
|
|
55
|
+
- **명령이 못 가는 곳에서도.** 측정 코드는 브라우저 스니펫 파일 하나입니다. 로그인한 세션을
|
|
56
|
+
포함해 JavaScript를 실행할 수 있는 곳이면 붙여 넣어 재고, 결과만 요약하면 됩니다.
|
|
57
|
+
|
|
58
|
+
| | page-load-metrics | Lighthouse | web-vitals |
|
|
59
|
+
|---|---|---|---|
|
|
60
|
+
| 질문 | 이 페이지가 느려졌나? | 이 페이지는 전체적으로 어떤가? | 실제 방문자에게 얼마나 빠른가? |
|
|
61
|
+
| 실행 | 차가운 로딩 3번, 중앙값 | 감사 1번 | 모든 실제 방문 |
|
|
62
|
+
| 지난번과 비교 | 됨 | 안 됨(직접 비교) | 분석 도구에서 |
|
|
63
|
+
| 페이지 코드 수정 필요 | 아니오 | 아니오 | 예 |
|
|
64
|
+
| 느린 휴대폰·회선 흉내 | `--throttle`(Lighthouse 모바일 기준) | 됨 | 실제 기기 |
|
|
65
|
+
|
|
66
|
+
## 설치
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
npx page-load-metrics https://example.com # 또는: npm install -g page-load-metrics
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Node 22 이상과 Google Chrome 또는 Chromium이 필요합니다. macOS와 Linux의 흔한 설치 위치에서
|
|
73
|
+
Chrome을 찾고, 못 찾으면 `--chrome PATH`나 `CHROME_PATH`로 알려 주면 됩니다.
|
|
74
|
+
|
|
75
|
+
## 빠르게 써 보기
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
page-load-metrics https://example.com # 1350x940에서 차가운 로딩 3번
|
|
79
|
+
page-load-metrics https://example.com --mobile # 412x915, 모바일 브라우저 정보
|
|
80
|
+
page-load-metrics https://example.com --mobile --throttle # 느린 4G와 CPU 4배 감속, 보급형 휴대폰 수준
|
|
81
|
+
page-load-metrics https://example.com --runs 5 # 더 많이 재서 중앙값 안정
|
|
82
|
+
page-load-metrics https://example.com --json # 요약, 직전 실행, 원본 결과 전부
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
기록은 `~/.local/state/page-load-metrics/history.jsonl`에 쌓입니다. 프로젝트별로 따로 두려면
|
|
86
|
+
`--store DIR`, 한 번만 재고 남기지 않으려면 `--no-save`를 씁니다.
|
|
87
|
+
|
|
88
|
+
## 로그인한 페이지
|
|
89
|
+
|
|
90
|
+
명령은 로그인하지 않은 새 브라우저를 띄웁니다. 로그인이 필요한 페이지는 내 세션에서 스니펫을
|
|
91
|
+
돌리고, 명령으로 요약합니다.
|
|
92
|
+
|
|
93
|
+
1. 로그인한 브라우저에서 페이지를 열고 강력 새로고침합니다.
|
|
94
|
+
2. 개발자 도구 콘솔(또는 자동화 도구의 evaluate 명령)에서 `page_load_metrics.js`를 실행합니다.
|
|
95
|
+
JSON 하나가 나오면 파일로 저장합니다.
|
|
96
|
+
3. 두 번 더 반복한 뒤 요약합니다.
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
page-load-metrics summarize run1.json run2.json run3.json
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`summarize`도 같은 표를 보여 주고 같은 기록에 남깁니다.
|
|
103
|
+
|
|
104
|
+
## 동작 방식
|
|
105
|
+
|
|
106
|
+
```mermaid
|
|
107
|
+
flowchart LR
|
|
108
|
+
A[새 브라우저 공간] --> B[페이지 열고 load 대기]
|
|
109
|
+
B --> C[스니펫이 성능 기록을 읽음]
|
|
110
|
+
C --> D[JSON 결과 하나]
|
|
111
|
+
D --> E{3번 했나?}
|
|
112
|
+
E -- 아니오 --> A
|
|
113
|
+
E -- 예 --> F[지표마다 중앙값과 등급]
|
|
114
|
+
F --> G[직전 저장 결과와 비교]
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
명령은 버리는 프로필로 헤드리스 Chrome을 띄우고, Node 내장 WebSocket으로 DevTools Protocol을
|
|
118
|
+
씁니다. 스니펫은 `load`를 기다린 뒤 늦은 그리기와 흔들림을 위해 2초 더 기다리고, 브라우저 자신의
|
|
119
|
+
성능 기록을 읽습니다.
|
|
120
|
+
|
|
121
|
+
## 참고
|
|
122
|
+
|
|
123
|
+
```
|
|
124
|
+
page-load-metrics URL [--runs 3] [--mobile | --viewport WxH] [--throttle] [--cpu N] [--settle 2000]
|
|
125
|
+
[--json] [--no-save] [--store DIR] [--chrome PATH] [--timeout 60000]
|
|
126
|
+
page-load-metrics summarize FILE... [--json] [--no-save] [--store DIR]
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
| 지표 | 뜻 | 좋음 / 개선 필요 / 나쁨 |
|
|
130
|
+
|---|---|---|
|
|
131
|
+
| `ttfb` | 문서의 첫 바이트가 오기까지 | ≤ 800 / ≤ 1800 / 초과 (ms) |
|
|
132
|
+
| `fcp` | 첫 내용이 그려지기까지 | ≤ 1800 / ≤ 3000 / 초과 (ms) |
|
|
133
|
+
| `lcp` | 가장 큰 내용이 그려지기까지, 그 요소 포함 | ≤ 2500 / ≤ 4000 / 초과 (ms) |
|
|
134
|
+
| `cls` | 화면 흔들림 누적(가장 큰 구간) | ≤ 0.1 / ≤ 0.25 / 초과 |
|
|
135
|
+
| `blocking` | 첫 그리기 뒤 메인 스레드가 막힌 시간, 총 차단 시간의 근사 | ≤ 200 / ≤ 600 / 초과 (ms) |
|
|
136
|
+
| `dom_content_loaded`, `load` | 내비게이션 시간 기록 | 등급 없음 |
|
|
137
|
+
| `transfer`, `requests` | 받은 바이트와 요청 수 | 등급 없음 |
|
|
138
|
+
|
|
139
|
+
등급 기준은 web.dev와 Lighthouse 실험실 기준을 따릅니다. `runs`는 그 지표를 알려 준 실행 수입니다.
|
|
140
|
+
스니펫 결과(`--json`의 `results`)에는 LCP 로딩·그리기 분해, 흔들린 요소 상위 목록, 막은 스크립트
|
|
141
|
+
상위 목록, 렌더링을 막는 파일, 가장 무거운 파일 8개도 들어 있습니다.
|
|
142
|
+
|
|
143
|
+
## 한계
|
|
144
|
+
|
|
145
|
+
- `--throttle` 없이 빠른 기기와 빠른 회선에서 잰 숫자는 낙관적입니다. `--throttle`은 Lighthouse
|
|
146
|
+
모바일 기준을 DevTools Protocol로 적용합니다: 요청 지연 562.5ms, 내려받기 1474.56Kbps, 올리기
|
|
147
|
+
675Kbps, CPU 4배 감속(`--cpu N`으로 배수 변경). CPU 감속은 재는 기기 기준이라 같은 기기에서 잰
|
|
148
|
+
결과끼리 비교하세요. 기록은 감속한 실행과 안 한 실행을 따로 비교합니다.
|
|
149
|
+
- 페이지 로딩만 잽니다. 클릭 반응(INP)은 실제 입력이 필요해서 재지 않습니다.
|
|
150
|
+
- 스니펫이 도는 페이지만 읽습니다. 다른 출처의 iframe과 워커는 빠집니다.
|
|
151
|
+
- `blocking`은 Chrome이 지원하면 긴 애니메이션 프레임을, 아니면 긴 작업을 씁니다. 둘 다 지원하지
|
|
152
|
+
않는 브라우저에서는 `n/a`입니다.
|
|
153
|
+
- `load` 뒤 2초만 기다리므로, 그 뒤에도 계속 움직이는 페이지의 흔들림은 덜 잡힐 수 있습니다.
|
|
154
|
+
|
|
155
|
+
## 기여
|
|
156
|
+
|
|
157
|
+
이슈와 풀 리퀘스트를 환영합니다. [CONTRIBUTING.md](CONTRIBUTING.md)를 보세요.
|
|
158
|
+
|
|
159
|
+
## 라이선스
|
|
160
|
+
|
|
161
|
+
[MIT](LICENSE)
|
package/README.md
CHANGED
|
@@ -1,3 +1,163 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<img src="https://raw.githubusercontent.com/elfenomenokim/page-load-metrics/main/docs/logo.svg" width="96" height="96" alt="A gauge over a page">
|
|
4
|
+
|
|
5
|
+
# page-load-metrics
|
|
6
|
+
|
|
7
|
+
Measure how fast a page loads, three cold loads at a time, and see what changed since last time.
|
|
8
|
+
|
|
9
|
+
[한국어](README.ko.md) · Node 22+ · Chrome · zero dependencies
|
|
10
|
+
|
|
11
|
+
[](https://github.com/elfenomenokim/page-load-metrics/actions/workflows/tests.yml)
|
|
12
|
+
[](https://www.npmjs.com/package/page-load-metrics)
|
|
13
|
+
[](LICENSE)
|
|
14
|
+
|
|
15
|
+
[Install](#install) · [Quick start](#quick-start) · [Signed-in pages](#signed-in-pages) · [Reference](#reference) · [Limits](#limits)
|
|
16
|
+
|
|
17
|
+
</div>
|
|
18
|
+
|
|
19
|
+
```console
|
|
20
|
+
$ npx page-load-metrics https://example.com
|
|
21
|
+
https://example.com · median of 3 cold loads · 1350x940
|
|
22
|
+
|
|
23
|
+
metric median rating change runs
|
|
24
|
+
------------------ ------ ------ -------------- ----
|
|
25
|
+
ttfb 117 ms good -8 ms (-6%) 3/3
|
|
26
|
+
fcp 188 ms good -52 ms (-22%) 3/3
|
|
27
|
+
lcp 236 ms good -116 ms (-33%) 3/3
|
|
28
|
+
cls 0 good 0 3/3
|
|
29
|
+
blocking 0 ms good 0 ms 3/3
|
|
30
|
+
dom_content_loaded 163 ms -11 ms (-6%) 3/3
|
|
31
|
+
load 164 ms -11 ms (-6%) 3/3
|
|
32
|
+
transfer 1.6 kB 0 kB (0%) 3/3
|
|
33
|
+
requests 1 0 (0%) 3/3
|
|
34
|
+
|
|
35
|
+
LCP element: p "Данный домен предназначен для "
|
|
36
|
+
change: against 2026-11-21T03:55:58.056Z
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
<sub>A real run from a Mac mini on 2026-11-21, the second of two; `change` compares it with the first. example.com served this machine its Russian text, which is why the LCP paragraph is in Russian.</sub>
|
|
40
|
+
|
|
41
|
+
## Why
|
|
42
|
+
|
|
43
|
+
You changed a page and want to know if it got slower. Lighthouse answers with a full audit
|
|
44
|
+
and a score; [web-vitals](https://github.com/GoogleChrome/web-vitals) answers from real users
|
|
45
|
+
once you ship it in your page. page-load-metrics answers the narrow question in seconds:
|
|
46
|
+
|
|
47
|
+
- **Cold every time.** Each run uses a fresh browser context, so no cache, cookies or service
|
|
48
|
+
worker carry over. The median of three runs hides one noisy load.
|
|
49
|
+
- **Change since last run.** Every result is saved per URL and viewport; the next run shows the
|
|
50
|
+
difference. Run it before and after a deploy.
|
|
51
|
+
- **Unknown stays unknown.** If the browser cannot report a metric, it is `n/a`, never a
|
|
52
|
+
reassuring zero.
|
|
53
|
+
- **Why it is slow, not just a score.** The LCP element with its load/render split, the nodes
|
|
54
|
+
that shifted, the scripts that blocked the main thread, and the heaviest files.
|
|
55
|
+
- **Works where a CLI cannot go.** The measuring code is one browser snippet. Paste it into any
|
|
56
|
+
session that can run JavaScript, including a signed-in one, and summarize the results.
|
|
57
|
+
|
|
58
|
+
| | page-load-metrics | Lighthouse | web-vitals |
|
|
59
|
+
|---|---|---|---|
|
|
60
|
+
| Question | did this page get slower? | how good is this page overall? | how fast is it for real users? |
|
|
61
|
+
| Runs | 3 cold loads, median | 1 audited load | every real visit |
|
|
62
|
+
| Compares with last run | yes | no (manual) | through your analytics |
|
|
63
|
+
| Needs your page's code | no | no | yes |
|
|
64
|
+
| Slow phone and network | `--throttle` (Lighthouse mobile preset) | yes | real devices |
|
|
65
|
+
|
|
66
|
+
## Install
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
npx page-load-metrics https://example.com # or: npm install -g page-load-metrics
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Needs Node 22 or newer and Google Chrome or Chromium. The CLI finds Chrome in the usual places
|
|
73
|
+
on macOS and Linux; otherwise pass `--chrome PATH` or set `CHROME_PATH`.
|
|
74
|
+
|
|
75
|
+
## Quick start
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
page-load-metrics https://example.com # 3 cold loads at 1350x940
|
|
79
|
+
page-load-metrics https://example.com --mobile # 412x915, mobile user agent
|
|
80
|
+
page-load-metrics https://example.com --mobile --throttle # slow 4G and 4x CPU, like a mid-range phone
|
|
81
|
+
page-load-metrics https://example.com --runs 5 # more runs, steadier median
|
|
82
|
+
page-load-metrics https://example.com --json # summary, previous run and every raw result
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
History lives in `~/.local/state/page-load-metrics/history.jsonl`. Use `--store DIR` to keep
|
|
86
|
+
one per project, or `--no-save` for a one-off.
|
|
87
|
+
|
|
88
|
+
## Signed-in pages
|
|
89
|
+
|
|
90
|
+
The CLI opens a fresh browser with no sign-in. For a page behind a login, run the snippet in
|
|
91
|
+
your own session and let the CLI summarize:
|
|
92
|
+
|
|
93
|
+
1. Open the page in a browser where you are signed in and hard-reload it.
|
|
94
|
+
2. Run `page_load_metrics.js` in the DevTools console (or through your automation tool's
|
|
95
|
+
evaluate command). It returns one JSON object. Save it to a file.
|
|
96
|
+
3. Repeat twice more, then:
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
page-load-metrics summarize run1.json run2.json run3.json
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`summarize` prints the same table and saves to the same history.
|
|
103
|
+
|
|
104
|
+
## How it works
|
|
105
|
+
|
|
106
|
+
```mermaid
|
|
107
|
+
flowchart LR
|
|
108
|
+
A[fresh browser context] --> B[navigate, wait for load]
|
|
109
|
+
B --> C[snippet reads performance entries]
|
|
110
|
+
C --> D[one JSON result]
|
|
111
|
+
D --> E{3 runs?}
|
|
112
|
+
E -- no --> A
|
|
113
|
+
E -- yes --> F[median and rating per metric]
|
|
114
|
+
F --> G[compare with last saved run]
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
The CLI starts headless Chrome with a throwaway profile and speaks the DevTools Protocol over
|
|
118
|
+
Node's built-in WebSocket. The snippet waits for `load`, then 2 seconds for late paints and
|
|
119
|
+
shifts, and reads the browser's own performance entries.
|
|
120
|
+
|
|
121
|
+
## Reference
|
|
122
|
+
|
|
123
|
+
```
|
|
124
|
+
page-load-metrics URL [--runs 3] [--mobile | --viewport WxH] [--throttle] [--cpu N] [--settle 2000]
|
|
125
|
+
[--json] [--no-save] [--store DIR] [--chrome PATH] [--timeout 60000]
|
|
126
|
+
page-load-metrics summarize FILE... [--json] [--no-save] [--store DIR]
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
| Metric | What it is | good / needs improvement / poor |
|
|
130
|
+
|---|---|---|
|
|
131
|
+
| `ttfb` | Time to first byte of the document | ≤ 800 / ≤ 1800 / more (ms) |
|
|
132
|
+
| `fcp` | First contentful paint | ≤ 1800 / ≤ 3000 / more (ms) |
|
|
133
|
+
| `lcp` | Largest contentful paint, with its element | ≤ 2500 / ≤ 4000 / more (ms) |
|
|
134
|
+
| `cls` | Cumulative layout shift (largest session window) | ≤ 0.1 / ≤ 0.25 / more |
|
|
135
|
+
| `blocking` | Main-thread blocking after FCP, approximates total blocking time | ≤ 200 / ≤ 600 / more (ms) |
|
|
136
|
+
| `dom_content_loaded`, `load` | Navigation timing endpoints | not rated |
|
|
137
|
+
| `transfer`, `requests` | Bytes over the network and resource count | not rated |
|
|
138
|
+
|
|
139
|
+
The bands follow web.dev and Lighthouse lab thresholds. `runs` shows how many runs reported the
|
|
140
|
+
metric. The snippet result (`--json` → `results`) also carries the LCP load/render split, the
|
|
141
|
+
top layout shifts with their nodes, the top blocking scripts, render-blocking files and the
|
|
142
|
+
eight heaviest resources.
|
|
143
|
+
|
|
144
|
+
## Limits
|
|
145
|
+
|
|
146
|
+
- Without `--throttle`, numbers from a fast machine on a fast line are optimistic. `--throttle`
|
|
147
|
+
applies Lighthouse's mobile preset through the DevTools Protocol: 562.5 ms request latency,
|
|
148
|
+
1474.56 Kbps down, 675 Kbps up and 4x CPU slowdown (`--cpu N` changes the factor). CPU slowdown
|
|
149
|
+
is relative to the machine you run on, so compare runs from the same machine. History keeps
|
|
150
|
+
throttled and unthrottled runs apart.
|
|
151
|
+
- One page load, not interactions. INP needs real input and is not measured.
|
|
152
|
+
- It reads the page it runs in. Cross-origin frames and workers are not included.
|
|
153
|
+
- `blocking` uses long animation frames where Chrome supports them, else long tasks; where the
|
|
154
|
+
browser supports neither it is `n/a`.
|
|
155
|
+
- The 2-second settle after `load` can miss shifts on pages that keep moving later.
|
|
156
|
+
|
|
157
|
+
## Contributing
|
|
158
|
+
|
|
159
|
+
Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
160
|
+
|
|
161
|
+
## License
|
|
162
|
+
|
|
163
|
+
[MIT](LICENSE)
|
package/cli.mjs
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// page-load-metrics: measure a URL several times in a fresh headless Chrome, report the
|
|
3
|
+
// median of each metric and the change since the last saved run of the same URL.
|
|
4
|
+
// Zero dependencies: Node 22 (built-in WebSocket) talks to Chrome over the DevTools Protocol.
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
7
|
+
import { homedir, tmpdir } from 'node:os';
|
|
8
|
+
import { dirname, join } from 'node:path';
|
|
9
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
10
|
+
import { parseArgs } from 'node:util';
|
|
11
|
+
|
|
12
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
const VERSION = JSON.parse(readFileSync(join(HERE, 'package.json'), 'utf8')).version;
|
|
14
|
+
const SNIPPET = readFileSync(join(HERE, 'page_load_metrics.js'), 'utf8');
|
|
15
|
+
|
|
16
|
+
// name, path in one snippet result, unit, rating bands (good <= a < needs-improvement <= b < poor)
|
|
17
|
+
export const FIELDS = [
|
|
18
|
+
['ttfb', 'metrics.ttfb.ms', 'ms', [800, 1800]],
|
|
19
|
+
['fcp', 'metrics.fcp.ms', 'ms', [1800, 3000]],
|
|
20
|
+
['lcp', 'metrics.lcp.ms', 'ms', [2500, 4000]],
|
|
21
|
+
['cls', 'metrics.cls.value', '', [0.1, 0.25]],
|
|
22
|
+
['blocking', 'metrics.blocking.blocking_ms', 'ms', [200, 600]],
|
|
23
|
+
['dom_content_loaded', 'metrics.dom_content_loaded', 'ms', null],
|
|
24
|
+
['load', 'metrics.load', 'ms', null],
|
|
25
|
+
['transfer', 'resources.transfer_kb', 'kB', null],
|
|
26
|
+
['requests', 'resources.count', '', null],
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
const pick = (obj, path) => path.split('.').reduce((o, k) => (o == null ? null : o[k]), obj) ?? null;
|
|
30
|
+
|
|
31
|
+
export function median(values) {
|
|
32
|
+
const v = values.filter((x) => typeof x === 'number' && Number.isFinite(x)).sort((a, b) => a - b);
|
|
33
|
+
if (!v.length) return null;
|
|
34
|
+
const m = v.length >> 1;
|
|
35
|
+
return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function rating(value, bands) {
|
|
39
|
+
if (value == null || !bands) return null;
|
|
40
|
+
return value <= bands[0] ? 'good' : value <= bands[1] ? 'needs-improvement' : 'poor';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Reduce several snippet results to one summary record.
|
|
44
|
+
export function summarize(runs, url = runs[0]?.url ?? null, setup = {}) {
|
|
45
|
+
const med = {};
|
|
46
|
+
for (const [name, path, , bands] of FIELDS) {
|
|
47
|
+
const values = runs.map((r) => pick(r, path));
|
|
48
|
+
const value = median(values);
|
|
49
|
+
med[name] = {
|
|
50
|
+
value: value == null ? null : Math.round(value * 1000) / 1000,
|
|
51
|
+
rating: rating(value, bands),
|
|
52
|
+
known: values.filter((x) => x != null).length,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
// LCP element from the run closest to the median LCP.
|
|
56
|
+
const lcpMed = med.lcp.value;
|
|
57
|
+
const lcpRun = lcpMed == null ? null
|
|
58
|
+
: [...runs].sort((a, b) => Math.abs((pick(a, 'metrics.lcp.ms') ?? 1e12) - lcpMed) - Math.abs((pick(b, 'metrics.lcp.ms') ?? 1e12) - lcpMed))[0];
|
|
59
|
+
const env = runs[0]?.env ?? {};
|
|
60
|
+
return {
|
|
61
|
+
tool: 'page-load-metrics',
|
|
62
|
+
version: VERSION,
|
|
63
|
+
at: new Date().toISOString(),
|
|
64
|
+
url,
|
|
65
|
+
final_url: runs[0]?.url ?? null,
|
|
66
|
+
runs: runs.length,
|
|
67
|
+
env: { viewport: env.viewport ?? null, dpr: env.dpr ?? null, mobile_ua: env.mobile_ua ?? null, throttle: setup.throttle ?? null },
|
|
68
|
+
median: med,
|
|
69
|
+
lcp_element: lcpRun ? pick(lcpRun, 'metrics.lcp.element') : null,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const sameSetup = (a, b) => a.url === b.url && a.env?.viewport === b.env?.viewport && a.env?.mobile_ua === b.env?.mobile_ua
|
|
74
|
+
&& (a.env?.throttle ?? null) === (b.env?.throttle ?? null);
|
|
75
|
+
|
|
76
|
+
export function previous(history, summary) {
|
|
77
|
+
for (let i = history.length - 1; i >= 0; i--) if (sameSetup(history[i], summary)) return history[i];
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const fmt = (v, unit) => (v == null ? 'n/a' : (unit === 'ms' || unit === '' && Number.isInteger(v) ? String(Math.round(v)) : String(v)) + (unit ? ' ' + unit : ''));
|
|
82
|
+
|
|
83
|
+
export function render(summary, prev) {
|
|
84
|
+
const rows = [['metric', 'median', 'rating', 'change', 'runs']];
|
|
85
|
+
for (const [name, , unit] of FIELDS) {
|
|
86
|
+
const m = summary.median[name];
|
|
87
|
+
const p = prev?.median?.[name]?.value;
|
|
88
|
+
let change = '';
|
|
89
|
+
if (prev && m.value != null && p != null) {
|
|
90
|
+
const d = Math.round((m.value - p) * 1000) / 1000;
|
|
91
|
+
change = (d > 0 ? '+' : '') + fmt(d, unit) + (p ? ` (${d > 0 ? '+' : ''}${Math.round((d / p) * 100)}%)` : '');
|
|
92
|
+
}
|
|
93
|
+
rows.push([name, fmt(m.value, unit), m.rating ?? '', change, `${m.known}/${summary.runs}`]);
|
|
94
|
+
}
|
|
95
|
+
const w = rows[0].map((_, i) => Math.max(...rows.map((r) => r[i].length)));
|
|
96
|
+
const lines = rows.map((r) => r.map((c, i) => c.padEnd(w[i])).join(' ').trimEnd());
|
|
97
|
+
lines.splice(1, 0, w.map((n) => '-'.repeat(n)).join(' '));
|
|
98
|
+
const head = `${summary.url} · median of ${summary.runs} cold loads · ${summary.env.viewport ?? '?'}${summary.env.mobile_ua ? ' mobile' : ''}${summary.env.throttle ? ' · ' + summary.env.throttle : ''}`;
|
|
99
|
+
const tail = [];
|
|
100
|
+
if (summary.lcp_element) tail.push(`LCP element: ${summary.lcp_element}`);
|
|
101
|
+
tail.push(prev ? `change: against ${prev.at}` : 'change: no earlier run of this URL, viewport and throttling');
|
|
102
|
+
return [head, '', ...lines, '', ...tail].join('\n');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function readHistory(file) {
|
|
106
|
+
if (!existsSync(file)) return [];
|
|
107
|
+
return readFileSync(file, 'utf8').split('\n').filter(Boolean).flatMap((l) => {
|
|
108
|
+
try { return [JSON.parse(l)]; } catch { return []; }
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ---------------------------------------------------------------- Chrome over CDP
|
|
113
|
+
|
|
114
|
+
function findChrome(explicit) {
|
|
115
|
+
const candidates = [
|
|
116
|
+
explicit,
|
|
117
|
+
process.env.CHROME_PATH,
|
|
118
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
119
|
+
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
120
|
+
'/usr/bin/google-chrome',
|
|
121
|
+
'/usr/bin/google-chrome-stable',
|
|
122
|
+
'/usr/bin/chromium',
|
|
123
|
+
'/usr/bin/chromium-browser',
|
|
124
|
+
'/snap/bin/chromium',
|
|
125
|
+
].filter(Boolean);
|
|
126
|
+
const found = candidates.find((p) => existsSync(p));
|
|
127
|
+
if (!found) throw new Error('Chrome not found; pass --chrome PATH or set CHROME_PATH');
|
|
128
|
+
return found;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
132
|
+
|
|
133
|
+
async function launch(chromePath) {
|
|
134
|
+
const profile = mkdtempSync(join(tmpdir(), 'page-load-metrics-'));
|
|
135
|
+
const proc = spawn(chromePath, [
|
|
136
|
+
'--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`,
|
|
137
|
+
'--no-first-run', '--no-default-browser-check', '--disable-extensions',
|
|
138
|
+
'--disable-background-networking', '--disable-component-update', '--mute-audio',
|
|
139
|
+
...(process.getuid?.() === 0 ? ['--no-sandbox'] : []),
|
|
140
|
+
'about:blank',
|
|
141
|
+
], { stdio: 'ignore' });
|
|
142
|
+
const portFile = join(profile, 'DevToolsActivePort');
|
|
143
|
+
for (let i = 0; i < 200 && !existsSync(portFile); i++) await sleep(50);
|
|
144
|
+
if (!existsSync(portFile)) { proc.kill(); throw new Error('Chrome did not open a DevTools port'); }
|
|
145
|
+
const [port, path] = readFileSync(portFile, 'utf8').trim().split('\n');
|
|
146
|
+
const exited = new Promise((r) => proc.once('exit', r));
|
|
147
|
+
const close = async () => {
|
|
148
|
+
try { proc.kill(); } catch {}
|
|
149
|
+
await Promise.race([exited, sleep(3000)]);
|
|
150
|
+
// Chrome's helper processes can still be writing for a moment after the main one exits.
|
|
151
|
+
try { rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } catch {}
|
|
152
|
+
};
|
|
153
|
+
return { ws: `ws://127.0.0.1:${port}${path}`, close };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function connect(url) {
|
|
157
|
+
return new Promise((resolve, reject) => {
|
|
158
|
+
const ws = new WebSocket(url);
|
|
159
|
+
let id = 0;
|
|
160
|
+
const pending = new Map();
|
|
161
|
+
const waiters = [];
|
|
162
|
+
ws.onmessage = (ev) => {
|
|
163
|
+
const msg = JSON.parse(ev.data);
|
|
164
|
+
if (msg.id && pending.has(msg.id)) {
|
|
165
|
+
const { ok, fail } = pending.get(msg.id);
|
|
166
|
+
pending.delete(msg.id);
|
|
167
|
+
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
|
|
168
|
+
} else if (msg.method) {
|
|
169
|
+
for (const w of [...waiters]) if (w.method === msg.method && w.sessionId === msg.sessionId) {
|
|
170
|
+
waiters.splice(waiters.indexOf(w), 1);
|
|
171
|
+
w.ok(msg.params);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
ws.onerror = () => reject(new Error('DevTools connection failed'));
|
|
176
|
+
ws.onopen = () => resolve({
|
|
177
|
+
send: (method, params = {}, sessionId) => new Promise((ok, fail) => {
|
|
178
|
+
const msgId = ++id;
|
|
179
|
+
pending.set(msgId, { ok, fail });
|
|
180
|
+
ws.send(JSON.stringify({ id: msgId, method, params, ...(sessionId ? { sessionId } : {}) }));
|
|
181
|
+
}),
|
|
182
|
+
once: (method, sessionId, timeoutMs) => new Promise((ok, fail) => {
|
|
183
|
+
const timer = setTimeout(() => { const i = waiters.indexOf(w); if (i >= 0) { waiters.splice(i, 1); fail(new Error(`timed out waiting for ${method}`)); } }, timeoutMs);
|
|
184
|
+
const w = { method, sessionId, ok: (v) => { clearTimeout(timer); ok(v); } };
|
|
185
|
+
waiters.push(w);
|
|
186
|
+
}),
|
|
187
|
+
close: () => ws.close(),
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Lighthouse's mobile preset ("Slow 4G", DevTools throttling): 150 ms RTT applied as 562.5 ms
|
|
193
|
+
// request latency, 1.6 Mbps down (1474.56 Kbps after the DevTools factor), 675 Kbps up, CPU 4x.
|
|
194
|
+
export const SLOW_4G = { latency: 562.5, downloadKbps: 1474.56, uploadKbps: 675 };
|
|
195
|
+
|
|
196
|
+
const MOBILE_UA = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36';
|
|
197
|
+
|
|
198
|
+
// One cold load: a new browser context (no cache, cookies or service workers), navigate, read.
|
|
199
|
+
async function measureOnce(cdp, url, opt) {
|
|
200
|
+
const { browserContextId } = await cdp.send('Target.createBrowserContext', { disposeOnDetach: true });
|
|
201
|
+
try {
|
|
202
|
+
const { targetId } = await cdp.send('Target.createTarget', { url: 'about:blank', browserContextId });
|
|
203
|
+
const { sessionId } = await cdp.send('Target.attachToTarget', { targetId, flatten: true });
|
|
204
|
+
const s = (m, p) => cdp.send(m, p, sessionId);
|
|
205
|
+
await s('Page.enable');
|
|
206
|
+
await s('Network.enable');
|
|
207
|
+
await s('Network.setCacheDisabled', { cacheDisabled: true });
|
|
208
|
+
await s('Emulation.setDeviceMetricsOverride', { width: opt.width, height: opt.height, deviceScaleFactor: opt.dpr, mobile: opt.mobile });
|
|
209
|
+
if (opt.mobile) await s('Emulation.setUserAgentOverride', { userAgent: MOBILE_UA });
|
|
210
|
+
if (opt.net) await s('Network.emulateNetworkConditions', {
|
|
211
|
+
offline: false, latency: opt.net.latency,
|
|
212
|
+
downloadThroughput: (opt.net.downloadKbps * 1024) / 8, uploadThroughput: (opt.net.uploadKbps * 1024) / 8,
|
|
213
|
+
});
|
|
214
|
+
if (opt.cpu > 1) await s('Emulation.setCPUThrottlingRate', { rate: opt.cpu });
|
|
215
|
+
const loaded = cdp.once('Page.loadEventFired', sessionId, opt.timeout);
|
|
216
|
+
const nav = await s('Page.navigate', { url });
|
|
217
|
+
if (nav.errorText) throw new Error(`navigation failed: ${nav.errorText}`);
|
|
218
|
+
await loaded;
|
|
219
|
+
const expr = `globalThis.PAGE_LOAD_METRICS_SETTLE_MS = ${opt.settle};\n${SNIPPET}`;
|
|
220
|
+
const r = await s('Runtime.evaluate', { expression: expr, awaitPromise: true, returnByValue: true, timeout: opt.timeout });
|
|
221
|
+
if (r.exceptionDetails) throw new Error(`snippet failed: ${r.exceptionDetails.exception?.description ?? r.exceptionDetails.text}`);
|
|
222
|
+
return r.result.value;
|
|
223
|
+
} finally {
|
|
224
|
+
await cdp.send('Target.disposeBrowserContext', { browserContextId }).catch(() => {});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export async function measure(url, opt) {
|
|
229
|
+
const chrome = await launch(findChrome(opt.chrome));
|
|
230
|
+
try {
|
|
231
|
+
const cdp = await connect(chrome.ws);
|
|
232
|
+
try {
|
|
233
|
+
const runs = [];
|
|
234
|
+
for (let i = 0; i < opt.runs; i++) {
|
|
235
|
+
runs.push(await measureOnce(cdp, url, opt));
|
|
236
|
+
if (!opt.quiet) process.stderr.write(`run ${i + 1}/${opt.runs} done\n`);
|
|
237
|
+
}
|
|
238
|
+
return runs;
|
|
239
|
+
} finally { cdp.close(); }
|
|
240
|
+
} finally { await chrome.close(); }
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ---------------------------------------------------------------- CLI
|
|
244
|
+
|
|
245
|
+
const USAGE = `page-load-metrics ${VERSION}
|
|
246
|
+
|
|
247
|
+
page-load-metrics URL [--runs 3] [--mobile | --viewport 1350x940] [--throttle] [--cpu N]
|
|
248
|
+
[--settle 2000] [--json] [--no-save] [--store DIR] [--chrome PATH]
|
|
249
|
+
page-load-metrics summarize FILE... [--json] [--no-save] [--store DIR]
|
|
250
|
+
|
|
251
|
+
Measures URL in fresh headless Chrome contexts (cold cache each run) and prints the median
|
|
252
|
+
of each metric with its rating and the change since the last saved run of the same URL and
|
|
253
|
+
viewport. 'summarize' does the same for snippet results you collected yourself, one JSON
|
|
254
|
+
object per file (or one per line), e.g. from a signed-in browser session.
|
|
255
|
+
--throttle applies Lighthouse's mobile preset: Slow 4G network and 4x CPU slowdown
|
|
256
|
+
(--cpu N changes the CPU factor; --cpu alone slows the CPU without network throttling).
|
|
257
|
+
History: --store DIR, default ~/.local/state/page-load-metrics/history.jsonl.`;
|
|
258
|
+
|
|
259
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
260
|
+
const { values: o, positionals } = parseArgs({
|
|
261
|
+
args: argv,
|
|
262
|
+
allowPositionals: true,
|
|
263
|
+
options: {
|
|
264
|
+
runs: { type: 'string', default: '3' },
|
|
265
|
+
mobile: { type: 'boolean', default: false },
|
|
266
|
+
throttle: { type: 'boolean', default: false },
|
|
267
|
+
cpu: { type: 'string' },
|
|
268
|
+
viewport: { type: 'string' },
|
|
269
|
+
settle: { type: 'string', default: '2000' },
|
|
270
|
+
json: { type: 'boolean', default: false },
|
|
271
|
+
'no-save': { type: 'boolean', default: false },
|
|
272
|
+
store: { type: 'string' },
|
|
273
|
+
chrome: { type: 'string' },
|
|
274
|
+
timeout: { type: 'string', default: '60000' },
|
|
275
|
+
help: { type: 'boolean', short: 'h', default: false },
|
|
276
|
+
version: { type: 'boolean', default: false },
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
if (o.version) return console.log(VERSION), 0;
|
|
280
|
+
if (o.help || !positionals.length) return console.log(USAGE), o.help ? 0 : 2;
|
|
281
|
+
|
|
282
|
+
let runs, url, throttle = null;
|
|
283
|
+
if (positionals[0] === 'summarize') {
|
|
284
|
+
runs = positionals.slice(1).flatMap((f) => {
|
|
285
|
+
const text = readFileSync(f, 'utf8').trim();
|
|
286
|
+
try { return [JSON.parse(text)]; } catch { return text.split('\n').filter(Boolean).map((l) => JSON.parse(l)); }
|
|
287
|
+
});
|
|
288
|
+
if (!runs.length) throw new Error('summarize needs at least one result file');
|
|
289
|
+
} else {
|
|
290
|
+
url = positionals[0];
|
|
291
|
+
const [w, h] = (o.viewport ?? (o.mobile ? '412x915' : '1350x940')).split('x').map(Number);
|
|
292
|
+
if (!w || !h) throw new Error('--viewport must look like 1350x940');
|
|
293
|
+
const cpu = o.cpu != null ? Math.max(1, Number(o.cpu) || 1) : o.throttle ? 4 : 1;
|
|
294
|
+
const net = o.throttle ? SLOW_4G : null;
|
|
295
|
+
throttle = [net && 'slow-4g', cpu > 1 && `cpu ${cpu}x`].filter(Boolean).join(' + ') || null;
|
|
296
|
+
runs = await measure(url, {
|
|
297
|
+
runs: Math.max(1, Number(o.runs) || 3), width: w, height: h, mobile: o.mobile, cpu, net,
|
|
298
|
+
dpr: o.mobile ? 2.625 : 1, settle: Math.max(0, Number(o.settle) || 0),
|
|
299
|
+
timeout: Number(o.timeout) || 60000, chrome: o.chrome, quiet: o.json,
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const summary = summarize(runs, url, { throttle });
|
|
304
|
+
const file = join(o.store ?? join(homedir(), '.local', 'state', 'page-load-metrics'), 'history.jsonl');
|
|
305
|
+
const prev = previous(readHistory(file), summary);
|
|
306
|
+
if (!o['no-save']) {
|
|
307
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
308
|
+
appendFileSync(file, JSON.stringify(summary) + '\n');
|
|
309
|
+
}
|
|
310
|
+
console.log(o.json ? JSON.stringify({ ...summary, previous: prev, results: runs }, null, 1) : render(summary, prev));
|
|
311
|
+
return 0;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
315
|
+
main().then((code) => process.exit(code), (err) => { console.error(`page-load-metrics: ${err.message}`); process.exit(1); });
|
|
316
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "page-load-metrics",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Measure a page several times in fresh headless Chrome, rate TTFB/FCP/LCP/CLS/blocking, and show the change since the last run. Zero dependencies; the snippet also runs in any browser session.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"cli.mjs",
|
|
8
|
+
"page_load_metrics.js"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"test": "node --test tests/page-load-metrics.test.mjs tests/cli.test.mjs"
|
|
12
|
+
},
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=22.18.0"
|
|
15
|
+
},
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/elfenomenokim/page-load-metrics"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"web-vitals",
|
|
23
|
+
"performance",
|
|
24
|
+
"lcp",
|
|
25
|
+
"cls",
|
|
26
|
+
"ttfb",
|
|
27
|
+
"browser",
|
|
28
|
+
"snippet",
|
|
29
|
+
"cli",
|
|
30
|
+
"headless-chrome",
|
|
31
|
+
"core-web-vitals"
|
|
32
|
+
],
|
|
33
|
+
"bin": {
|
|
34
|
+
"page-load-metrics": "cli.mjs"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/elfenomenokim/page-load-metrics#readme",
|
|
37
|
+
"bugs": {
|
|
38
|
+
"url": "https://github.com/elfenomenokim/page-load-metrics/issues"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Page load metrics read inside the page with the browser's own performance entries.
|
|
2
|
+
// Evaluate after a load, e.g.
|
|
3
|
+
// bsk reload --hard --session SID && bsk evaluate --json --session SID "$(cat page_load_metrics.js)"
|
|
4
|
+
// Returns one JSON object; every number is milliseconds unless named *_kb or cls.
|
|
5
|
+
// Ratings follow web.dev / Lighthouse lab bands; blocking_ms approximates TBT.
|
|
6
|
+
/*
|
|
7
|
+
* Reads the load timing of the page it runs in. Override the post-load settle wait with
|
|
8
|
+
* `globalThis.PAGE_LOAD_METRICS_SETTLE_MS` (milliseconds, default 2000); any other
|
|
9
|
+
* value, including 0, is used as-is when it is a finite non-negative number.
|
|
10
|
+
*/
|
|
11
|
+
(async () => {
|
|
12
|
+
const SETTLE_MS = (() => {
|
|
13
|
+
const raw = Number(globalThis.PAGE_LOAD_METRICS_SETTLE_MS);
|
|
14
|
+
return Number.isFinite(raw) && raw >= 0 ? raw : 2000;
|
|
15
|
+
})();
|
|
16
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
17
|
+
if (document.readyState !== "complete") {
|
|
18
|
+
await new Promise((r) => addEventListener("load", r, { once: true }));
|
|
19
|
+
}
|
|
20
|
+
await sleep(SETTLE_MS);
|
|
21
|
+
|
|
22
|
+
const supported = PerformanceObserver.supportedEntryTypes || [];
|
|
23
|
+
const buffered = async (type) => {
|
|
24
|
+
if (!supported.includes(type)) return null;
|
|
25
|
+
const out = [];
|
|
26
|
+
const po = new PerformanceObserver((l) => out.push(...l.getEntries()));
|
|
27
|
+
po.observe({ type, buffered: true });
|
|
28
|
+
await sleep(50);
|
|
29
|
+
out.push(...po.takeRecords());
|
|
30
|
+
po.disconnect();
|
|
31
|
+
return out;
|
|
32
|
+
};
|
|
33
|
+
const round = (v) => (v == null ? null : Math.round(v));
|
|
34
|
+
const kb = (b) => Math.round(b / 102.4) / 10;
|
|
35
|
+
const short = (u) => {
|
|
36
|
+
try {
|
|
37
|
+
const x = new URL(u, location.href);
|
|
38
|
+
return (x.origin === location.origin ? "" : x.host) + x.pathname.slice(-60);
|
|
39
|
+
} catch { return String(u).slice(-60); }
|
|
40
|
+
};
|
|
41
|
+
const desc = (el) => {
|
|
42
|
+
if (!el || !el.tagName) return null;
|
|
43
|
+
let s = el.tagName.toLowerCase();
|
|
44
|
+
if (el.id) s += "#" + el.id;
|
|
45
|
+
const cls = typeof el.className === "string" ? el.className.trim().split(/\s+/).slice(0, 2) : [];
|
|
46
|
+
if (cls[0]) s += "." + cls.join(".");
|
|
47
|
+
if (el.currentSrc || el.src) s += " " + short(el.currentSrc || el.src);
|
|
48
|
+
else if (el.textContent) s += ' "' + el.textContent.trim().slice(0, 30) + '"';
|
|
49
|
+
return s;
|
|
50
|
+
};
|
|
51
|
+
const rate = (v, good, poor) => (v == null ? null : v <= good ? "good" : v <= poor ? "needs-improvement" : "poor");
|
|
52
|
+
|
|
53
|
+
const nav = performance.getEntriesByType("navigation")[0];
|
|
54
|
+
const ttfb = nav ? Math.max(0, nav.responseStart - (nav.activationStart || 0)) : null;
|
|
55
|
+
const paints = (await buffered("paint")) || performance.getEntriesByType("paint");
|
|
56
|
+
const fcp = paints.find((e) => e.name === "first-contentful-paint")?.startTime ?? null;
|
|
57
|
+
|
|
58
|
+
const resources = performance.getEntriesByType("resource");
|
|
59
|
+
const lcpEntry = ((await buffered("largest-contentful-paint")) || []).at(-1) || null;
|
|
60
|
+
let lcp = null;
|
|
61
|
+
if (lcpEntry) {
|
|
62
|
+
// Text elements produce LCP entries without a resource; their load phases are zero.
|
|
63
|
+
// Without navigation timing the phases are unknown (null), never computed from zero.
|
|
64
|
+
const res = lcpEntry.url ? resources.find((r) => r.name === lcpEntry.url) : null;
|
|
65
|
+
const base = ttfb ?? 0;
|
|
66
|
+
const loadStart = res ? Math.max(base, res.requestStart || res.startTime) : base;
|
|
67
|
+
const loadEnd = res ? Math.max(loadStart, res.responseEnd) : base;
|
|
68
|
+
const at = Math.max(loadEnd, lcpEntry.startTime);
|
|
69
|
+
const phase = (v) => (ttfb == null ? null : round(v));
|
|
70
|
+
lcp = {
|
|
71
|
+
ms: round(at),
|
|
72
|
+
element: desc(lcpEntry.element) || (lcpEntry.url ? short(lcpEntry.url) : "(removed from the page)"),
|
|
73
|
+
size: lcpEntry.size,
|
|
74
|
+
ttfb: round(ttfb),
|
|
75
|
+
load_delay: phase(loadStart - base),
|
|
76
|
+
load_duration: phase(loadEnd - loadStart),
|
|
77
|
+
render_delay: phase(at - loadEnd),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// An entry type the browser does not support is unknown (null), not a good zero.
|
|
82
|
+
const shiftEntries = await buffered("layout-shift");
|
|
83
|
+
const shifts = (shiftEntries || []).filter((e) => !e.hadRecentInput);
|
|
84
|
+
let cls = 0, win = 0, winStart = 0, prev = 0;
|
|
85
|
+
for (const e of shifts) {
|
|
86
|
+
if (win && (e.startTime - prev > 1000 || e.startTime - winStart > 5000)) win = 0;
|
|
87
|
+
if (!win) winStart = e.startTime;
|
|
88
|
+
win += e.value;
|
|
89
|
+
prev = e.startTime;
|
|
90
|
+
cls = Math.max(cls, win);
|
|
91
|
+
}
|
|
92
|
+
const shiftSources = shifts
|
|
93
|
+
.sort((a, b) => b.value - a.value)
|
|
94
|
+
.slice(0, 3)
|
|
95
|
+
.map((e) => ({
|
|
96
|
+
at: round(e.startTime),
|
|
97
|
+
value: Math.round(e.value * 1000) / 1000,
|
|
98
|
+
nodes: (e.sources || []).map((s) => desc(s.node)).filter(Boolean).slice(0, 2),
|
|
99
|
+
}));
|
|
100
|
+
|
|
101
|
+
// Main-thread blocking after FCP: long animation frames, else long tasks.
|
|
102
|
+
let blocking = null;
|
|
103
|
+
const loaf = await buffered("long-animation-frame");
|
|
104
|
+
if (loaf) {
|
|
105
|
+
const after = loaf.filter((f) => fcp == null || f.startTime >= fcp);
|
|
106
|
+
const scripts = after.flatMap((f) => f.scripts || []).sort((a, b) => b.duration - a.duration);
|
|
107
|
+
blocking = {
|
|
108
|
+
source: "long-animation-frame",
|
|
109
|
+
frames: after.length,
|
|
110
|
+
blocking_ms: round(after.reduce((s, f) => s + f.blockingDuration, 0)),
|
|
111
|
+
longest_ms: round(Math.max(0, ...after.map((f) => f.duration))),
|
|
112
|
+
top_scripts: scripts.slice(0, 3).map((s) => ({
|
|
113
|
+
ms: round(s.duration),
|
|
114
|
+
source: short(s.sourceURL || "") + (s.sourceFunctionName ? " " + s.sourceFunctionName : ""),
|
|
115
|
+
invoker: String(s.invoker || "").slice(0, 60),
|
|
116
|
+
})),
|
|
117
|
+
};
|
|
118
|
+
} else if (supported.includes("longtask")) {
|
|
119
|
+
const tasks = ((await buffered("longtask")) || []).filter((t) => fcp == null || t.startTime >= fcp);
|
|
120
|
+
blocking = {
|
|
121
|
+
source: "longtask",
|
|
122
|
+
frames: tasks.length,
|
|
123
|
+
blocking_ms: round(tasks.reduce((s, t) => s + Math.max(0, t.duration - 50), 0)),
|
|
124
|
+
longest_ms: round(Math.max(0, ...tasks.map((t) => t.duration))),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const bytes = (r) => r.transferSize || r.encodedBodySize || 0;
|
|
129
|
+
const byType = {};
|
|
130
|
+
for (const r of resources) {
|
|
131
|
+
const t = (byType[r.initiatorType] ||= { count: 0, transfer_kb: 0 });
|
|
132
|
+
t.count += 1;
|
|
133
|
+
t.transfer_kb += kb(r.transferSize || 0);
|
|
134
|
+
}
|
|
135
|
+
for (const t of Object.values(byType)) t.transfer_kb = Math.round(t.transfer_kb * 10) / 10;
|
|
136
|
+
const files = [...resources]
|
|
137
|
+
.sort((a, b) => bytes(b) - bytes(a))
|
|
138
|
+
.slice(0, 8)
|
|
139
|
+
.map((r) => ({
|
|
140
|
+
file: short(r.name),
|
|
141
|
+
type: r.initiatorType,
|
|
142
|
+
kb: kb(bytes(r)),
|
|
143
|
+
ms: round(r.duration),
|
|
144
|
+
cached: r.transferSize === 0 && r.decodedBodySize > 0,
|
|
145
|
+
blocking: r.renderBlockingStatus === "blocking",
|
|
146
|
+
}));
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
url: location.href,
|
|
150
|
+
env: {
|
|
151
|
+
viewport: innerWidth + "x" + innerHeight,
|
|
152
|
+
dpr: devicePixelRatio,
|
|
153
|
+
mobile_ua: /Mobi|Android/.test(navigator.userAgent),
|
|
154
|
+
network: navigator.connection?.effectiveType ?? null,
|
|
155
|
+
nav_type: nav?.type ?? null,
|
|
156
|
+
document_from_cache: nav ? nav.transferSize === 0 : null,
|
|
157
|
+
settle_ms: SETTLE_MS,
|
|
158
|
+
},
|
|
159
|
+
metrics: {
|
|
160
|
+
ttfb: { ms: round(ttfb), rating: rate(ttfb, 800, 1800) },
|
|
161
|
+
fcp: { ms: round(fcp), rating: rate(fcp, 1800, 3000) },
|
|
162
|
+
lcp: lcp && { ...lcp, rating: rate(lcp.ms, 2500, 4000) },
|
|
163
|
+
cls: shiftEntries
|
|
164
|
+
? { value: Math.round(cls * 1000) / 1000, rating: rate(cls, 0.1, 0.25), top_shifts: shiftSources }
|
|
165
|
+
: { value: null, rating: null, top_shifts: [] },
|
|
166
|
+
blocking: blocking && { ...blocking, rating: rate(blocking.blocking_ms, 200, 600) },
|
|
167
|
+
dom_content_loaded: round(nav?.domContentLoadedEventEnd),
|
|
168
|
+
load: round(nav?.loadEventEnd),
|
|
169
|
+
},
|
|
170
|
+
resources: {
|
|
171
|
+
count: resources.length,
|
|
172
|
+
transfer_kb: Math.round(resources.reduce((s, r) => s + kb(r.transferSize || 0), 0) * 10) / 10,
|
|
173
|
+
document_kb: nav ? kb(nav.transferSize || nav.encodedBodySize || 0) : null,
|
|
174
|
+
size_hidden: resources.filter((r) => !bytes(r)).length,
|
|
175
|
+
by_type: byType,
|
|
176
|
+
render_blocking: resources.filter((r) => r.renderBlockingStatus === "blocking").map((r) => short(r.name)),
|
|
177
|
+
heaviest: files,
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
})()
|