├── .github
└── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── eslint.config.js
├── layout-shift-gif.js
├── package-lock.json
└── package.json
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: workeffortwaste
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | *.png
3 | *.gif
4 | *.json
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Layout Shift GIF Generator - CLI
2 |
3 | [https://defaced.dev/tools/layout-shift-gif-generator/](https://defaced.dev/tools/layout-shift-gif-generator/)
4 |
5 | _Visualise the Core Web Vitals metric Cumulative Layout Shift (CLS) with a simple GIF._
6 |
7 | Lighthouse is a great tool for identifying your overall Cumulative Layout Shift (CLS) score, but it's not so great for quickly visualising what's actually shifting on a page. The Layout Shift GIF Generator allows you to quickly identify which elements are moving around in the viewport.
8 |
9 | > **Support this project**
Help support the work that goes into creating and maintaining my projects and sponsor me via [GitHub Sponsors](https://github.com/sponsors/workeffortwaste/).
10 |
11 | ## Contents
12 |
13 | - [Layout Shift GIF Generator - CLI](#layout-shift-gif-generator---cli)
14 | - [Contents](#contents)
15 | - [What's New](#whats-new)
16 | - [1.4.0 🆕](#140-)
17 | - [Getting Started](#getting-started)
18 | - [Installation](#installation)
19 | - [Usage](#usage)
20 | - [Options](#options)
21 | - [Examples](#examples)
22 | - [Basic Examples](#basic-examples)
23 | - [Simulated Mobile Device](#simulated-mobile-device)
24 | - [Simulated Desktop Device](#simulated-desktop-device)
25 | - [Advanced Examples](#advanced-examples)
26 | - [Supplying Cookies](#supplying-cookies)
27 | - [Original CLS Calculation Method](#original-cls-calculation-method)
28 | - [Device Simulation](#device-simulation)
29 | - [Save JSON Report 🆕](#save-json-report-)
30 | - [Hosted Version](#hosted-version)
31 | - [Output](#output)
32 | - [Page Screenshot](#page-screenshot)
33 | - [Border Style](#border-style)
34 | - [Border Colour](#border-colour)
35 | - [Corner Metric](#corner-metric)
36 | - [Corner Colour](#corner-colour)
37 | - [Sponsors](#sponsors)
38 | - [Bonus](#bonus)
39 | - [Author](#author)
40 |
41 |
42 | ## What's New
43 |
44 | ### 1.4.0 🆕
45 |
46 | * Updated core dependencies including Puppeteer (Chromium) to the latest version to give more accurate readings.
47 | * Added the option to save a JSON report of shifted elements and their CSS selectors with the `--report` flag.
48 |
49 | ## Getting Started
50 |
51 | ### Installation
52 |
53 | The Layout Shift GIF Generator command line tool can be installed directly from NPM.
54 |
55 | ```
56 | npm install -g layout-shift-gif
57 | ```
58 |
59 | ### Usage
60 |
61 | Once installed the tool can be used as per the following example.
62 |
63 | ```
64 | layout-shift-gif --url https://blacklivesmatter.com/ --device mobile --output layout-shift.gif
65 | ```
66 |
67 | This will generate an animated `layout-shift.gif` of `https://blacklivesmatter.com/` showing the regions of Cumulative Layout Shift on the viewport of a simulated `mobile` device.
68 |
69 | ### Options
70 |
71 | ```
72 | Options:
73 | --help Show help [boolean]
74 | --version Show version number [boolean]
75 | -u, --url Website URL [string] [required]
76 | -d, --device Device type [string] [default: "mobile"]
77 | -w, --width Device viewport width [number]
78 | -h, --height Device viewport height [number]
79 | -c, --cookies Cookie filename [string]
80 | -o, --output Output filename [string] [default: "layout-shift.gif"]
81 | -t, --type CLS calculation method [string] [default: "new"]
82 | -r, --report Save report of shifts and elements [boolean] [default: false]
83 | ```
84 | ## Examples
85 | ### Basic Examples
86 |
87 | #### Simulated Mobile Device
88 |
89 | ```
90 | layout-shift-gif --url https://blacklivesmatter.com/ --device mobile
91 | ```
92 |
93 | #### Simulated Desktop Device
94 |
95 | ```
96 | layout-shift-gif --url https://blacklivesmatter.com/ --device desktop
97 | ```
98 |
99 | ### Advanced Examples
100 |
101 | #### Supplying Cookies
102 |
103 | You can supply a cookie file in the Puppeteer JSON format allowing you to bypass cookie notices, or interstitals.
104 |
105 | I recommend using the [Export cookie JSON file for Puppeteer](https://chrome.google.com/webstore/detail/%E3%82%AF%E3%83%83%E3%82%AD%E3%83%BCjson%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%87%BA%E5%8A%9B-for-puppet/nmckokihipjgplolmcmjakknndddifde?hl=en) Chrome extension to export your cookies in the correct format.
106 |
107 | ```
108 | layout-shift-gif --url https://blacklivesmatter.com/ --cookies cookies.json
109 | ```
110 |
111 | #### Original CLS Calculation Method
112 |
113 | In June 2021 Google changed how they [calculate the CLS metric](https://web.dev/cls-web-tooling/). Layout Shift GIF Generator defaults to the newest method, but if you require the old method it can still be access viable the `--type` option.
114 |
115 |
116 | ```
117 | layout-shift-gif --url https://blacklivesmatter.com/ --type old
118 | ```
119 |
120 | ## Device Simulation
121 |
122 | The tool is able to check both a desktop and a mobile viewport.
123 |
124 | - The `desktop` viewport is a standard 1920x1080 resolution.
125 |
126 | - The `mobile` viewport is the Nexus 5X profile from Lighthouse.
127 |
128 | Both the CPU and the network are throttled to simulate a `good 3G network`.
129 |
130 | ## Save JSON Report 🆕
131 |
132 | The tool is able to create a corresponding JSON report including the full CSS selectors for every element triggering a shift.
133 |
134 | ```
135 | layout-shift-gif --url https://blacklivesmatter.com/ --report
136 | ```
137 |
138 | ## Hosted Version
139 |
140 | If you don't wish to use the CLI version there is also a free hosted version running in a cloud function available on [defaced.dev](https://defaced.dev/tools/layout-shift-gif-generator/)
141 |
142 | ## Output
143 |
144 | An outline of how to interpret the GIF output from this tool.
145 |
146 | ### Page Screenshot
147 |
148 | The screenshot of the page is taken after all the page elements have shifted and the CLS has been calculated.
149 |
150 | ### Border Style
151 |
152 | The border style of an outlined element represents the start and end positions of the elements shift.
153 |
154 | - A `dashed` border indicates the element's starting position.
155 |
156 | - A `solid` border indicates the element's end position.
157 |
158 | ### Border Colour
159 |
160 | The border colour of an outlined element represents the CLS score of that element against the overall page thresholds for CLS [outlined by Google](https://web.dev/defining-core-web-vitals-thresholds/).
161 |
162 | 🟢 Good `≤` 0.1
163 |
164 | 🟠 Needs Improvement
165 |
166 | 🔴 Poor `>` 0.25
167 |
168 | This means that if you see a shifting element with a red or orange outline then this element alone is contributing significantly to a negative CLS score for that page.
169 |
170 | ### Corner Metric
171 |
172 | The metric in the top left corner is the overall CLS score for that page and is the score you'll see in Lighthouse or Pagespeed Insights.
173 |
174 | ### Corner Colour
175 |
176 | The colour of the top left corner represents where the pages overall CLS score fits within the thresholds for CLS [outlined by Google](https://web.dev/defining-core-web-vitals-thresholds/).
177 |
178 | 🟢 Good `≤` 0.1
179 |
180 | 🟠 Needs Improvement
181 |
182 | 🔴 Poor `>` 0.25
183 |
184 | ## Sponsors
185 |
186 | If you find this project useful please considering sponsoring me on [GitHub Sponsors](https://github.com/sponsors/workeffortwaste/) and help support the work that goes into creating and maintaining my projects.
187 |
188 | ### Bonus
189 |
190 | Sponsors are able to remove the project support message from all my CLI projects, as well as access other additional perks.
191 |
192 | ## Author
193 |
194 | Chris Johnson - [defaced.dev](https://defaced.dev) - [@defaced.dev](https://bsky.app/profile/defaced.dev) (Bluesky)
195 |
--------------------------------------------------------------------------------
/eslint.config.js:
--------------------------------------------------------------------------------
1 | import neostandard from 'neostandard'
2 |
3 | export default neostandard({})
4 |
--------------------------------------------------------------------------------
/layout-shift-gif.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | /*
4 | * SPDX-License-Identifier: Apache-2.0
5 | */
6 |
7 | /* Args */
8 | import yargs from 'yargs'
9 | import { hideBin } from 'yargs/helpers'
10 |
11 | /* Puppeteer */
12 | import puppeteer from 'puppeteer-extra'
13 | import StealthPlugin from 'puppeteer-extra-plugin-stealth'
14 |
15 | /* Misc */
16 | import fs from 'fs'
17 | import tmp from 'tmp'
18 |
19 | /* Image generation */
20 | import GIFEncoder from 'gif-encoder-2'
21 | import pkg from 'canvas'
22 | const { createCanvas, loadImage } = pkg
23 |
24 | /* Evade bot detection */
25 | puppeteer.use(StealthPlugin())
26 |
27 | /* Colors */
28 | const colors = {
29 | reset: '\x1b[0m',
30 | underscore: '\x1b[4m',
31 | magenta: '\x1b[35m',
32 | blue: '\x1b[34m',
33 | green: '\x1b[32m',
34 | red: '\x1b[31m',
35 | yellow: '\x1b[33m'
36 | }
37 |
38 | /* About */
39 | const { version } = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url)))
40 | console.log(`layout-shift-gif ${version} / ${colors.blue}@defaced.dev (bluesky)${colors.reset}`)
41 |
42 | /* Support */
43 | if (!process.env.WORKEFFORTWASTE_SUPPORTER) {
44 | console.log(`${colors.magenta}
45 | ┃
46 | ┃ ${colors.underscore}Support this project! ${colors.reset}${colors.magenta}
47 | ┃
48 | ┃ Help support the work that goes into creating and maintaining my projects
49 | ┃ and consider donating via on GitHub Sponsors.
50 | ┃
51 | ┃ GitHub Sponsors: https://github.com/sponsors/workeffortwaste/
52 | ┃${colors.reset}
53 | `)
54 | }
55 |
56 | const options = yargs(hideBin(process.argv))
57 | .usage('Usage: layout-shift-gif --url ')
58 | .example('layout-shift-gif --url https://blacklivesmatter.com/ --device mobile --output layout-shift.gif')
59 | .default({ d: 'mobile', o: 'layout-shift.gif', t: 'new', r: false })
60 | .describe('u', 'Website URL')
61 | .describe('d', 'Device type')
62 | .describe('w', 'Device viewport width')
63 | .describe('h', 'Device viewport height')
64 | .describe('c', 'Cookie filename')
65 | .describe('o', 'Output filename')
66 | .describe('t', 'CLS calculation method')
67 | .describe('r', 'Save report of shifts and elements')
68 | .alias('u', 'url')
69 | .alias('d', 'device')
70 | .alias('w', 'width')
71 | .alias('h', 'height')
72 | .alias('c', 'cookies')
73 | .alias('o', 'output')
74 | .alias('r', 'report')
75 | .alias('t', 'type')
76 | .number(['h', 'w'])
77 | .string(['u', 'd', 'c', 'o', 't'])
78 | .boolean(['r'])
79 | .demandOption(['url'])
80 | .epilogue('For more information visit documentation at: \nhttp://github.com/workeffortwaste/layout-shift-gif')
81 | .argv
82 |
83 | /* Network conditions */
84 | const Good3G = {
85 | offline: false,
86 | downloadThroughput: 1.5 * 1024 * 1024 / 8,
87 | uploadThroughput: 750 * 1024 / 8,
88 | latency: 40
89 | }
90 |
91 | /* Device for mobile emulation */
92 | const phone = {
93 | name: 'Nexus 5X',
94 | userAgent: 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
95 | viewport: {
96 | width: 412,
97 | height: 732,
98 | deviceScaleFactor: 2.625,
99 | isMobile: true,
100 | hasTouch: true,
101 | isLandscape: false
102 | }
103 | }
104 |
105 | /* Detect layout shift */
106 | const clsDetection = (type) => {
107 | const getElementSelector = (element) => {
108 | if (!element) return null
109 |
110 | const parts = []
111 |
112 | while (element.parentElement) {
113 | let part = element.tagName.toLowerCase() // Tag name in lowercase
114 |
115 | // Add ID if present
116 | if (element.id) {
117 | part += `#${element.id}`
118 | }
119 |
120 | // Add classes if present
121 | if (element.className) {
122 | const classes = element.className.trim().split(/\s+/).join('.')
123 | part += `.${classes}`
124 | }
125 |
126 | // Add :nth-child if necessary
127 | const siblings = Array.from(element.parentElement.children)
128 | if (siblings.filter(el => el.tagName === element.tagName).length > 1) {
129 | const index = siblings.indexOf(element) + 1
130 | part += `:nth-child(${index})`
131 | }
132 |
133 | parts.unshift(part) // Add the part to the beginning of the array
134 | element = element.parentElement // Move up to the parent
135 | }
136 |
137 | // Include `body` or `html` as the root
138 | parts.unshift(element.tagName.toLowerCase())
139 |
140 | return parts.join(' > ')
141 | }
142 |
143 | window.cumulativeLayoutShiftScore = 0
144 | window.previousRect = []
145 | window.currentRect = []
146 | window.shifts = []
147 | window.sources = []
148 | let firstTs = Number.NEGATIVE_INFINITY
149 | let prevTs = Number.NEGATIVE_INFINITY
150 |
151 | const observer = new PerformanceObserver((list) => {
152 | for (const entry of list.getEntries()) {
153 | if (entry.hadRecentInput) continue
154 | if (type === 'new') {
155 | if (entry.startTime - firstTs > 5000 || entry.startTime - prevTs > 1000) {
156 | firstTs = entry.startTime
157 | window.cumulativeLayoutShiftScore = 0
158 | window.shifts = []
159 | }
160 | prevTs = entry.startTime
161 | }
162 |
163 | entry.sources.forEach((e) => {
164 | window.previousRect.push(JSON.parse(JSON.stringify(e.previousRect)))
165 | window.currentRect.push(JSON.parse(JSON.stringify(e.currentRect)))
166 | window.shifts.push(entry.value)
167 | })
168 |
169 | window.sources.push({
170 | value: entry.value,
171 | elements: entry.sources.map((s) => getElementSelector(s.node))
172 | })
173 |
174 | window.cumulativeLayoutShiftScore += entry.value
175 |
176 | window.onload = (event) => {
177 | observer.takeRecords()
178 | observer.disconnect()
179 | }
180 | }
181 | })
182 | observer.observe({ type: 'layout-shift', buffered: true })
183 | }
184 |
185 | // Return the colours we're using for the CLS
186 | const getColor = (cls) => {
187 | let c = {
188 | stroke: 'rgba(0,128,0,.7)',
189 | fill: 'rgba(0,128,0,.1)',
190 | solid: 'rgb(0,128,0,1)'
191 | }
192 |
193 | if (cls > 0.1) {
194 | c = {
195 | stroke: 'rgba(255,125,0,.5)',
196 | fill: 'rgba(255,125,0,.05)',
197 | solid: 'rgba(255,125,0,1)'
198 | }
199 | }
200 |
201 | if (cls > 0.25) {
202 | c = {
203 | stroke: 'rgba(255,0,0,.5)',
204 | fill: 'rgba(255,0,0,.05)',
205 | solid: 'rgba(255,0,0,1)'
206 | }
207 | }
208 |
209 | return c
210 | }
211 |
212 | const createGif = async (url, device) => {
213 | // Launch puppeteer
214 | const browser = await puppeteer.launch({ ignoreHTTPSErrors: true, args: ['--no-sandbox'], timeout: 10000 })
215 |
216 | try {
217 | const page = await browser.newPage()
218 | if (options.cookies) {
219 | const cookies = JSON.parse(fs.readFileSync(options.cookies))
220 | await page.setCookie(...cookies)
221 | }
222 | const client = await page.target().createCDPSession()
223 | await client.send('Network.enable')
224 | await client.send('ServiceWorker.enable')
225 |
226 | // Throttle the network and CPU to give us a chance to actually capture layout shifts.
227 | await client.send('Network.emulateNetworkConditions', Good3G)
228 | await client.send('Emulation.setCPUThrottlingRate', { rate: 4 })
229 |
230 | // Emulate a phone or standard desktop size.
231 | if (device === 'mobile') {
232 | await page.emulate(phone)
233 | await page.setViewport({
234 | width: 412,
235 | height: 732,
236 | deviceScaleFactor: 1
237 | })
238 | // Override viewport resolution if a width or height are manually supplied
239 | if (options.width || options.height) {
240 | await page.setViewport({
241 | width: options.width || page.viewport().width,
242 | height: options.height || page.viewport().height,
243 | deviceScaleFactor: 1
244 | })
245 | }
246 | } else {
247 | // Override viewport resolution if a width or height are manually supplied
248 | await page.setViewport({
249 | width: options.width || 1920,
250 | height: options.height || 1080
251 | })
252 | }
253 |
254 | // Initiate clsDetection at the earliest possible moment
255 | await page.evaluateOnNewDocument(clsDetection, options.type)
256 |
257 | // Navigate to the page and wait until it's hit the load event, 120s timeout for tries
258 | await page.goto(url, { waitUntil: 'load', timeout: 120000 })
259 |
260 | // Populate an object for everything we need to draw our final images
261 | const output = await page.evaluate(() => {
262 | return {
263 | score: window.cumulativeLayoutShiftScore,
264 | previousRect: window.previousRect,
265 | currentRect: window.currentRect,
266 | shifts: window.shifts,
267 | report: {
268 | url: window.location.href,
269 | cls: window.cumulativeLayoutShiftScore,
270 | entries: window.sources
271 | }
272 | }
273 | })
274 | output.scaleFactor = page.viewport().deviceScaleFactor || 1
275 |
276 | // Set up the tmp directory
277 | const tmpobj = tmp.dirSync()
278 |
279 | // Take a screenshot of the page after it's loaded.
280 | await page.screenshot({ path: tmpobj.name + '/temp-screenshot.png' })
281 |
282 | // Close the browser.
283 | browser.close()
284 |
285 | // Load the puppeteer screenshot from the fs
286 | const image = await loadImage(tmpobj.name + '/temp-screenshot.png')
287 |
288 | // Start a gif encoder at the resolution of our screenshot
289 | const encoder = new GIFEncoder(image.width, image.height)
290 |
291 | // GIF encoder settings
292 | encoder.start()
293 | encoder.setRepeat(0) // 0 for repeat, -1 for no-repeat
294 | encoder.setDelay(500) // frame delay in ms
295 | encoder.setQuality(20) // image quality. 10 is default.
296 |
297 | // Create our canvas
298 | const canvas = createCanvas(image.width, image.height)
299 | const ctx = canvas.getContext('2d')
300 |
301 | // Canvas setup function
302 | const canvasSetup = () => {
303 | // Add the screenshot to each frame
304 | ctx.drawImage(image, 0, 0, image.width, image.height)
305 | // Add the CLS score in the top left corner
306 | ctx.beginPath()
307 | ctx.rect(0, 0, 110 * output.scaleFactor, 36 * output.scaleFactor)
308 | ctx.fillStyle = getColor(output.score).solid
309 | ctx.fill()
310 | ctx.lineWidth = 2 * output.scaleFactor
311 | ctx.fillStyle = 'white'
312 | ctx.font = 18 * output.scaleFactor + 'px Arial'
313 | ctx.fillText('CLS: ' + output.score.toFixed(3), 8 * output.scaleFactor, 24 * output.scaleFactor)
314 | }
315 | // Setup the canvas for the first frame
316 | canvasSetup()
317 |
318 | // Output the first frame rects
319 | output.currentRect.forEach((d, k) => {
320 | ctx.strokeStyle = getColor(output.shifts[k]).stroke
321 | ctx.fillStyle = getColor(output.shifts[k]).fill
322 | ctx.beginPath()
323 | ctx.rect(d.x * output.scaleFactor, d.y * output.scaleFactor, d.width * output.scaleFactor, d.height * output.scaleFactor)
324 | ctx.stroke()
325 | ctx.fill()
326 | })
327 | // Add frame to the GIF
328 | encoder.addFrame(ctx)
329 |
330 | // Clear the first frame
331 | ctx.clearRect(0, 0, canvas.width, canvas.height)
332 |
333 | // Setup the canvas for the second frame
334 | canvasSetup()
335 |
336 | // Output the the second frame rects
337 | ctx.setLineDash([5 * output.scaleFactor, 3 * output.scaleFactor])
338 | output.previousRect.forEach((d, k) => {
339 | ctx.strokeStyle = getColor(output.shifts[k]).stroke
340 | ctx.fillStyle = getColor(output.shifts[k]).fill
341 | ctx.beginPath()
342 | ctx.rect(d.x * output.scaleFactor, d.y * output.scaleFactor, d.width * output.scaleFactor, d.height * output.scaleFactor)
343 | ctx.stroke()
344 | ctx.fill()
345 | })
346 | // Add frame to the GIF
347 | encoder.addFrame(ctx)
348 |
349 | // Write the GIF
350 | encoder.finish()
351 | fs.writeFileSync(options.output, encoder.out.getData())
352 |
353 | // Save the report if requested
354 | if (options.report) {
355 | fs.writeFileSync(options.output.replace('.gif', '.json'), JSON.stringify(output.report))
356 | }
357 |
358 | // Pass back the CLS score
359 | return output.score.toFixed(3)
360 | } catch (error) {
361 | browser.close()
362 | throw (error)
363 | }
364 | }
365 |
366 | createGif(options.url, options.device, options.filename)
367 | .then(e => {
368 | let scoreColor = colors.green
369 |
370 | if (e > 0.1) scoreColor = colors.yellow
371 | if (e > 0.25) scoreColor = colors.red
372 |
373 | console.log(`Cumulative layout shift (CLS) ${scoreColor}${e}${colors.reset}`)
374 | console.log(`Image succesfully saved as ${colors.blue}${options.output}${colors.reset}`)
375 | if (options.report) console.log(`Report succesfully saved as ${colors.blue}${options.output.replace('.gif', '.json')}${colors.reset}`)
376 | })
377 | .catch(e => console.log(e))
378 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "layout-shift-gif",
3 | "version": "1.4.0",
4 | "description": "Generates a .gif showing the layout shift events for a website.",
5 | "main": "./layout-shift-gif.js",
6 | "keywords": [
7 | "layout shift",
8 | "cls",
9 | "gif",
10 | "cumulative layout shift",
11 | "web vitals"
12 | ],
13 | "repository": {
14 | "type": "git",
15 | "url": "git+https://github.com/workeffortwaste/layout-shift-gif.git"
16 | },
17 | "author": "Chris Johnson (https://defaced.dev)",
18 | "license": "ISC",
19 | "type": "module",
20 | "dependencies": {
21 | "canvas": "^3.0.1",
22 | "gif-encoder-2": "^1.0.5",
23 | "puppeteer": "^23.11.1",
24 | "puppeteer-extra": "^3.3.6",
25 | "puppeteer-extra-plugin-stealth": "^2.11.2",
26 | "tmp": "^0.2.3",
27 | "yargs": "^17.7.2"
28 | },
29 | "bin": {
30 | "layout-shift-gif": "./layout-shift-gif.js"
31 | },
32 | "bugs": {
33 | "url": "https://github.com/workeffortwaste/layout-shift-gif/issues"
34 | },
35 | "homepage": "https://defaced.dev/tools/layout-shift-gif-generator/",
36 | "devDependencies": {
37 | "eslint": "^9.17.0",
38 | "neostandard": "^0.12.0"
39 | }
40 | }
41 |
--------------------------------------------------------------------------------