Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LCP & Above the Fold Optimization #6311

Merged
merged 227 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
227 commits
Select commit Hold shift + click to select a range
5887986
Add service provider
remyperona Oct 16, 2023
a00b471
missing extension
remyperona Oct 16, 2023
596d515
Add Database classes for Above the fold optimization (#6208)
remyperona Oct 16, 2023
0fe186a
Merge branch 'develop' into feature/lcp-above-the-fold-optimization
remyperona Oct 31, 2023
66f9dda
Merge branch 'develop' into feature/lcp-above-the-fold-optimization
remyperona Nov 9, 2023
536ae0d
Merge branch 'develop' into feature/lcp-above-the-fold-optimization
jeawhanlee Nov 28, 2023
274e72a
Frontend module for LCP & Above the fold Optimization (#6244)
jeawhanlee Dec 6, 2023
9e73f94
Merge branch 'develop' into feature/lcp-above-the-fold-optimization
remyperona Dec 7, 2023
b3392c0
Closes #6284 LCP & ATF: admin part (#6285)
remyperona Dec 14, 2023
b0d1b4e
Closes #6281: Task/lcp refactor rucss api cron queue (#6307)
jeawhanlee Dec 15, 2023
92f1b13
Updated table interface name
jeawhanlee Dec 15, 2023
818e4b0
Fixes #6323: Get the actual title tag of the document and use as rege…
jeawhanlee Dec 15, 2023
0b20b40
Closes #6319 Create SaaS global clear and banners (#6328)
remyperona Dec 15, 2023
cedc02e
Fixes: #6322: Guard LCP filter from wrong value (#6326)
jeawhanlee Dec 15, 2023
a8bef5a
fix import, remove unused methods
remyperona Dec 15, 2023
32b2a5c
Closes #6321: LCP/ATF relative images not excluded from LL (#6336)
jeawhanlee Dec 18, 2023
5bc4249
Fixes #6325 Detect existing fetchpriority attribute when spaces aroun…
remyperona Jan 2, 2024
b7ab514
Updated optimization type
jeawhanlee Jan 10, 2024
a8dc3f0
Merged remote branch of github.com:wp-media/wp-rocket into feature/lc…
jeawhanlee Jan 10, 2024
fcd6b46
Refactor clean RUCSS/Critical images dashboard button (#6334)
remyperona Jan 15, 2024
56dbb5f
Closes #6461: Delete old implementation lcp
Miraeld Mar 13, 2024
1a6ceac
Delete last reference to `atf_factory`
Miraeld Mar 13, 2024
9955b99
Closes #6461: Deletes old implementation LCP (#6475)
Miraeld Mar 14, 2024
1b55af5
Revert "Closes #6461: Deletes old implementation LCP" (#6483)
jeawhanlee Mar 14, 2024
8ada5e2
Remove atf_factory from $factories array
Miraeld Mar 15, 2024
9b098e8
Closes #6474: Update maintenance for LCP/ATF
Miraeld Mar 19, 2024
127b57f
Swap function from ATFTable to ATFQuery
Miraeld Mar 19, 2024
b271071
Closes #6474: Update maintenance LCP/ATF (#6489)
Miraeld Mar 20, 2024
e1fcffa
Fix Conflicts
Miraeld Mar 20, 2024
15499c5
Merge branch 'fix/6461-clean-old-implementation' into feature/lcp-abo…
Miraeld Mar 20, 2024
0253e4b
Closes #6461: Delete old implementation lcp
Miraeld Mar 20, 2024
4b7046b
Closes #6461: Delete old implementation lcp (#6499)
Miraeld Mar 20, 2024
6a831f4
Merge branch 'feature/lcp-above-the-fold-optimization' of https://git…
remyperona Mar 20, 2024
d234139
Closes #6500: Use correct table name (#6501)
jeawhanlee Mar 20, 2024
c8a9bb6
Closes #6430: Inject beacon script to page (#6459)
Miraeld Mar 20, 2024
f854ef1
Closes #6479 Add inline JS data for LCP script (#6481)
remyperona Mar 20, 2024
ca4a55b
Closes #6431 AJAX insertion of LCP data (#6488)
remyperona Mar 20, 2024
36e820c
prevent duplicate entries
remyperona Mar 20, 2024
63b724f
Apply missing dimensions with our query string (#6484)
wordpressfan Mar 20, 2024
5227550
Sub-task: #6429 preload links with actions (#6465)
jeawhanlee Mar 20, 2024
63ec831
Remove extra coma from schema data (#6502)
jeawhanlee Mar 21, 2024
e6bc66a
minify lcp script
remyperona Mar 21, 2024
a1af0b8
Merge branch 'develop' into feature/lcp-above-the-fold-optimization
remyperona Mar 21, 2024
2a96d0a
Closes #6354: Tests for RUCSS API & CRON Refactor (#6356)
jeawhanlee Mar 22, 2024
f311790
Closes #6470 Send links to SaaS for warmup (#6503)
wordpressfan Mar 22, 2024
15739a7
Closes #6428 Bail-out of warmup if licence expired since more than 15…
Khadreal Mar 22, 2024
d50d339
update version to 3.16-alpha1
remyperona Mar 22, 2024
68978f7
update last version to 3.15.10
remyperona Mar 22, 2024
719ca6c
Closes #6506: Fatal error activating 3.16 pre alpha (#6508)
jeawhanlee Mar 25, 2024
8c31595
Fixes #6511 - 3.16 - In some cases DOMContentLoaded is already fired …
wordpressfan Mar 26, 2024
e901296
Fix has_lcp condition
MathieuLamiot Mar 26, 2024
873edb0
Comply phpcs
Miraeld Mar 28, 2024
c5ebde3
Add tests
Miraeld Mar 28, 2024
b15585c
Fix tests
Miraeld Mar 28, 2024
1f6cd21
Fix the new linter rule about parenthisis and precendence of && and ||
MathieuLamiot Mar 28, 2024
11fa968
remaining linter errors
MathieuLamiot Mar 28, 2024
475fdec
Revert "remaining linter errors"
MathieuLamiot Mar 28, 2024
2aa4c50
Revert "Fix the new linter rule about parenthisis and precendence of …
MathieuLamiot Mar 28, 2024
f488281
Give it another try
MathieuLamiot Mar 28, 2024
b459f19
316 bug front end optimizations are not applied even when lcpatf data…
MathieuLamiot Mar 29, 2024
5380658
Closes #6527: Images intersecting the viewport will be considered as …
Miraeld Apr 9, 2024
4daa66f
Updated text
jeawhanlee Apr 9, 2024
ac6d186
Merge branch 'develop' into feature/lcp-above-the-fold-optimization
remyperona Apr 9, 2024
ca50f74
fix merge
remyperona Apr 9, 2024
37d0e26
Merge branch 'feature/lcp-above-the-fold-optimization' into fix/6533-…
jeawhanlee Apr 9, 2024
aec0c3d
Closes #6518: Inject beacon for saas visit
Miraeld Apr 9, 2024
1308890
Closes #6432: Adds conditions to bail out from beacon
Miraeld Apr 10, 2024
699c3fc
fix PHP warning
remyperona Apr 10, 2024
1b02783
Fix integrations tests
Miraeld Apr 11, 2024
30393e8
Comply feedback
Miraeld Apr 11, 2024
3d25cc6
Move rocket_after_clear_atf firing in delete_rows to make sure it fir…
MathieuLamiot Mar 26, 2024
8820380
Fix linter
MathieuLamiot Apr 9, 2024
5970f74
:chore: Add data attribute to --fixes :bug: #6521
Khadreal Apr 11, 2024
03bf1a6
Closes #6533: Inconsistency between Clear used CSS / Critical Images …
MathieuLamiot Apr 12, 2024
a34a5d1
fix PHP warning
remyperona Apr 10, 2024
ad5706f
:chore: Add data attribute to --fixes :bug: #6521
Khadreal Apr 11, 2024
13f31b0
Merge branch 'bug/saas-results-db#6521' of github.com:wp-media/wp-roc…
Khadreal Apr 12, 2024
853e0cd
:chore: Add beacon header to request
Khadreal Apr 12, 2024
e31b05b
Closes #6518: inject beacon for saas (#6548)
MathieuLamiot Apr 12, 2024
7376232
Merge commit 'e31b05b9bb505b7955627c49b1f53acd503f2060' into bug/saas…
MathieuLamiot Apr 12, 2024
9a13da7
Add integration tests
Miraeld Apr 12, 2024
9caaef7
:closes: Fixed test and update minify js
Khadreal Apr 15, 2024
eded04b
Merge branch 'bug/saas-results-db#6521' of github.com:wp-media/wp-roc…
Khadreal Apr 15, 2024
1b5ca43
Resolve test issue :feat:
Khadreal Apr 15, 2024
d74e2a6
Fixed test
Khadreal Apr 15, 2024
58f8343
Comply feedback
Miraeld Apr 15, 2024
1c4062a
3.16 bug the warm up of lcpatf is not triggered when clicking clear c…
Miraeld Apr 15, 2024
1450d9a
:feat: Update id and notice message #6526
Khadreal Apr 16, 2024
7947b65
Closes #6527: Images intersecting viewport considered as lcp candidat…
Miraeld Apr 16, 2024
88ceebf
Change notice error id :close: #6526
Khadreal Apr 16, 2024
ee58ad6
Merge branch 'develop' into feature/lcp-above-the-fold-optimization
remyperona Apr 16, 2024
a2240ab
update service provider with new container version
remyperona Apr 16, 2024
38775e5
update service provider with new container version
remyperona Apr 16, 2024
3b8f3c0
update admin condition for clear critical images on URL
remyperona Apr 16, 2024
97c4f61
Closes #6552: Wrong type captured in DB
Miraeld Apr 16, 2024
3dbfd0a
Closes #6535: Preload the image-set background images
Miraeld Apr 16, 2024
f343a3f
Closes #6534: Preload the layered bg img
Miraeld Apr 16, 2024
9a5dbc1
Closes #6532: Preload the single bg img
Miraeld Apr 16, 2024
7cb4fcd
Closes #6531: Preload responsive images
Miraeld Apr 16, 2024
9707faf
Closes #6530: Preload pictures tags
Miraeld Apr 16, 2024
bd07079
Apply linter
Miraeld Apr 16, 2024
52c5d80
clean code
Miraeld Apr 16, 2024
a06c5cf
Fix unit tests
Miraeld Apr 16, 2024
4131eb2
Fix integrations tests
Miraeld Apr 16, 2024
dcf4bd4
Comply feedback
Miraeld Apr 16, 2024
73f603e
Merge branch 'feature/lcp-above-the-fold-optimization' into enhanceme…
Miraeld Apr 17, 2024
538fbb1
Update lcp-beacon
Miraeld Apr 17, 2024
c6a7c1e
Update lcp-beacon
Miraeld Apr 17, 2024
6ea8df5
Merge branch 'refs/heads/develop' into feature/lcp-above-the-fold-opt…
wordpressfan Apr 17, 2024
3c7281a
fix conflicts with activation
wordpressfan Apr 17, 2024
132a9f0
fix atf serviceprovider to match the new container
wordpressfan Apr 17, 2024
0ed1f71
Merge branch 'feature/lcp-above-the-fold-optimization' into enhanceme…
Miraeld Apr 18, 2024
5d51e47
Fix/update default fetched links to 10 and parse unappended url to is…
jeawhanlee Apr 18, 2024
cbf5840
Update lcp-beacon for atf
Miraeld Apr 18, 2024
0a85128
Closes #6553: Frontend optimization applied for the wrong element in …
jeawhanlee Apr 18, 2024
9cf1b8e
Update notice messages
Khadreal Apr 19, 2024
ac6cefa
Merge branch 'develop' into enhancement/6432-bail-out-from-beacon-con…
Miraeld Apr 19, 2024
ed582a8
Change conditions to bail out
Miraeld Apr 19, 2024
3e43699
Merge branch 'feature/lcp-above-the-fold-optimization' into enhanceme…
Miraeld Apr 19, 2024
fb9a475
Closes #6536: ATF image in root not excluded from root with specific …
jeawhanlee Apr 19, 2024
bea4037
:feat: Change occurence of old transient key, update tests and fixed …
Khadreal Apr 19, 2024
e523287
fixed lint
Khadreal Apr 19, 2024
e246da6
Add unit test for add_clean_saas_menu_item()
remyperona Apr 19, 2024
af00697
Merge branch 'develop' into feature/lcp-above-the-fold-optimization
remyperona Apr 19, 2024
fb81d0a
Merge branch 'feature/lcp-above-the-fold-optimization' into fix/6509-…
remyperona Apr 19, 2024
b75d299
Add svg supports + fix isIntersecting
Miraeld Apr 22, 2024
36967aa
:chore: Optimise LCP beacon script #6537
Khadreal Apr 22, 2024
48e1129
:sparkles: add wpr filter for lcp/atf elements
Khadreal Apr 22, 2024
a5600ca
Modified existing tests
Khadreal Apr 22, 2024
523ba6b
Uncomment code
Khadreal Apr 22, 2024
7450f95
Optimise beacon script based on feedback #6537
Khadreal Apr 22, 2024
0b1dede
add safe guard for links limit filter value
remyperona Apr 22, 2024
5a9d445
Implement review
Khadreal Apr 23, 2024
29494ac
Replace "@covers" with "Test class covering" on lcp/atf branch
MathieuLamiot Apr 23, 2024
b844ed5
Merge commit '52bde305e6a1feb018fe92808fa79dd111db0d79' into test/cov…
MathieuLamiot Apr 23, 2024
6cdbb85
escape url when saving lcp into the database and when putting the dat…
wordpressfan Apr 23, 2024
1fe5e80
Remove rss feed links and rest api links from warm up links
jeawhanlee Apr 23, 2024
97f519c
Updated tests
jeawhanlee Apr 23, 2024
c846b00
phpcs fix
jeawhanlee Apr 23, 2024
e78014f
Add new method to handle image dimension :close: #6569
Khadreal Apr 23, 2024
caea1a8
Test/cover markup for lcp atf branch (#6583)
MathieuLamiot Apr 23, 2024
b13ad6e
Updated test data to cover scenario (#6585)
jeawhanlee Apr 23, 2024
3d45079
fix typo
remyperona Apr 23, 2024
8e2ba0a
add unit tests for add_clean_url_menu_item
remyperona Apr 23, 2024
66356a9
Fixes #6509 Don't display clear critical images for this URL on admin…
Miraeld Apr 24, 2024
3eb619b
Merge branch 'refs/heads/feature/lcp-above-the-fold-optimization' int…
wordpressfan Apr 24, 2024
66efbf9
stub esc functions
wordpressfan Apr 24, 2024
3db779b
Removed treeshake parameter and inidicate start and end process on log
jeawhanlee Apr 24, 2024
a402098
Updated tests
jeawhanlee Apr 24, 2024
aee078d
phpcs fix
jeawhanlee Apr 24, 2024
5ffdbb2
add error log
Khadreal Apr 24, 2024
ddb54f0
add filter for image dimension
Khadreal Apr 24, 2024
0f815b7
Add context check for imagedimension method
Khadreal Apr 24, 2024
707a402
Fixed lint, remove test data
Khadreal Apr 24, 2024
ea90e83
Merge branch 'branch-3.16' into feature/lcp-above-the-fold-optimization
remyperona Apr 24, 2024
e5a3150
Merge branch 'feature/lcp-above-the-fold-optimization' of https://git…
remyperona Apr 24, 2024
44e5116
Merge branch 'branch-3.16' into feature/lcp-above-the-fold-optimization
remyperona Apr 24, 2024
41f5192
Closes #6530 #6531 #6532 #6534 #6535 #6552: Preload images markup (#6…
Miraeld Apr 24, 2024
5f8292a
Enhancement/preload background image atf (#6579)
Miraeld Apr 24, 2024
063c7d9
Add test
Khadreal Apr 24, 2024
2486a81
Fixes #6576 Add safe guard for links limit filter value in warmup (#6…
MathieuLamiot Apr 24, 2024
d3e45fd
Fixed code conflict
Khadreal Apr 24, 2024
172c5ba
Updated REGEX
jeawhanlee Apr 24, 2024
8714682
Updated test data
jeawhanlee Apr 24, 2024
501e0cf
Merged branch feature/lcp-above-the-fold-optimization into fix/6575-s…
jeawhanlee Apr 24, 2024
549d524
Merge branch 'feature/lcp-above-the-fold-optimization' into enhanceme…
Miraeld Apr 25, 2024
b174327
Update lcp-beacon.min.js
Miraeld Apr 25, 2024
bad9d46
Fix linter
Miraeld Apr 25, 2024
d783638
Fix linter
Miraeld Apr 25, 2024
3f46bf6
Closes #6432: Bail out from beacon conditions (#6555)
Miraeld Apr 25, 2024
6040562
Fix bail out
Miraeld Apr 25, 2024
550e05d
Fixed failing test and code conflict
Khadreal Apr 25, 2024
6748e41
fixed integration test typo
Khadreal Apr 25, 2024
91077f9
Fixed sass do not store result in DB bug (#6557)
Khadreal Apr 25, 2024
9a7ff94
Use reject uri pattern directly for cases when helper function is used
jeawhanlee Apr 25, 2024
bb87e92
Updated test
jeawhanlee Apr 25, 2024
cb0e327
add some unit tests and limit the atf image numbers
wordpressfan Apr 25, 2024
13a59ea
fix phpcs
wordpressfan Apr 25, 2024
7a2e90e
Merge branch 'refs/heads/feature/lcp-above-the-fold-optimization' int…
wordpressfan Apr 25, 2024
fabcefa
fix after merge
wordpressfan Apr 25, 2024
4577210
guard against not valid lcp
wordpressfan Apr 25, 2024
15fa830
add a check if the url is relative url so use sanitize_text_field bec…
wordpressfan Apr 25, 2024
3fef09c
fix phpcs and adjust is_relative method
wordpressfan Apr 25, 2024
0383656
Fix LCP result when no LCP on page
Miraeld Apr 25, 2024
0ba3af3
Merge branch 'feature/lcp-above-the-fold-optimization' into fix/6591-…
Miraeld Apr 25, 2024
efab65e
Fix conflicts
Miraeld Apr 25, 2024
e33c614
Fix lcp-beacon
Miraeld Apr 25, 2024
01c2664
adjust is_relative conditions
wordpressfan Apr 25, 2024
4bea22a
Closes #6591: LCP/ATF data is malformed when no LCP is found by the b…
Miraeld Apr 25, 2024
6367399
fix tests, hopefully
wordpressfan Apr 25, 2024
287c5f2
Merge branch 'refs/heads/feature/lcp-above-the-fold-optimization' int…
wordpressfan Apr 25, 2024
fc062c3
Change values of threshold + safeguard
Miraeld Apr 25, 2024
64ede3e
Merge branch 'feature/lcp-above-the-fold-optimization' into enhanceme…
Miraeld Apr 25, 2024
8901e29
Fix beacon min + map
Miraeld Apr 25, 2024
d288c85
Fix integrations tests
Miraeld Apr 25, 2024
9a9e1f4
Closes #6432: Bail out from beacon (screen size) threshold modificati…
MathieuLamiot Apr 25, 2024
ccb07c7
Fixed reviews
Khadreal Apr 25, 2024
6af9077
Fix lint error
Khadreal Apr 25, 2024
8836a19
add debug value to data
remyperona Apr 25, 2024
730a33f
update test case
remyperona Apr 25, 2024
407ca9f
use debug value
remyperona Apr 25, 2024
02ff403
:feat: PR review modifications
Khadreal Apr 25, 2024
dff7e74
fix lint error :sparkles:
Khadreal Apr 25, 2024
b935c75
Fix #6526 LCP/ATF messages that is not working correctly (#6562)
MathieuLamiot Apr 25, 2024
92cf653
Closes #6575: Should not fetch rss feed or rest api links from homepa…
MathieuLamiot Apr 25, 2024
48cf824
remove unused variable
remyperona Apr 25, 2024
6cdc57b
update tests
remyperona Apr 25, 2024
bf54b60
fix tests
remyperona Apr 25, 2024
7304078
fix tests
remyperona Apr 25, 2024
44af1da
Merge branch 'fix/6574-beacon-console' into fix/6591-lcp-atf-data-mal…
Miraeld Apr 26, 2024
e095147
Encode LCP to JSON if correct format
Miraeld Apr 26, 2024
d77956b
Add bail-out safeguard
Miraeld Apr 26, 2024
a7e7ae8
Added tests
Miraeld Apr 26, 2024
1ea967d
Fix linter
Miraeld Apr 26, 2024
439ec0a
Closes #6569: Add image dimension query to Saas request (#6588)
MathieuLamiot Apr 26, 2024
a76706b
Fixes #6574 Display console message only in debug mode (#6595)
remyperona Apr 26, 2024
b651fee
Task/6471 remove treeshake param and provide logs of sent requests (#…
MathieuLamiot Apr 26, 2024
f67703d
Deletes Bail out, and change the way we manage no lcp
Miraeld Apr 26, 2024
deae0ed
Closes #6591: LCP/ATF data is malformed when no LCP is found by the b…
MathieuLamiot Apr 26, 2024
1b0c95b
Merge branch 'feature/lcp-above-the-fold-optimization' into enhanceme…
remyperona Apr 26, 2024
764aaf2
update the method returning the list of elements for lcp/atf
remyperona Apr 26, 2024
5a93f89
remove unnecessary condition
remyperona Apr 26, 2024
5915e16
Fix unit tests
Miraeld Apr 29, 2024
6123325
Add Integrations tests
Miraeld Apr 29, 2024
7e3e48f
Apply more strict security rules with LCP (#6584)
Miraeld Apr 29, 2024
43b073c
3.16 - Refactor beacon script and notify SaaS that we completed with …
wordpressfan Apr 29, 2024
8b19f21
Merge branch 'branch-3.16' into feature/lcp-above-the-fold-optimization
remyperona Apr 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
315 changes: 315 additions & 0 deletions assets/js/lcp-beacon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,315 @@
class RocketLcpBeacon {
constructor( config ) {
this.config = config;
this.performanceImages = [];
}

init() {
if ( ! this._isValidPreconditions() ) {
this._finalize();
return;
}

// Use _generateLcpCandidates method to get all the elements in the viewport.
const above_the_fold_images = this._generateLcpCandidates( Infinity );
if ( above_the_fold_images ) {
this._initWithFirstElementWithInfo( above_the_fold_images );
this._fillATFWithoutDuplications( above_the_fold_images );
}

this._saveFinalResultIntoDB();
}

_isValidPreconditions() {
// Check the screensize first because starting any logic.
if ( this._isNotValidScreensize() ) {
this._logMessage('Bailing out because screen size is not acceptable');
return false;
}

if ( this._isGeneratedBefore() ) {
this._logMessage('Bailing out because data is already available');
return false;
}

return true;
}

_isGeneratedBefore() {
// AJAX call to check if there are any records for the current URL.
let data_check = new FormData();
data_check.append('action', 'rocket_check_lcp');
data_check.append('rocket_lcp_nonce', this.config.nonce);
data_check.append('url', this.config.url);
data_check.append('is_mobile', this.config.is_mobile);

const lcp_data_response = fetch(this.config.ajax_url, {
method: "POST",
credentials: 'same-origin',
body: data_check
});

return lcp_data_response.success;
}

_isNotValidScreensize() {
// Check screen size
const screenWidth = window.innerWidth || document.documentElement.clientWidth;
const screenHeight= window.innerHeight || document.documentElement.clientHeight;

const isNotValidForMobile = this.config.is_mobile &&
( screenWidth > this.config.width_threshold || screenHeight > this.config.height_threshold );
const isNotValidForDesktop = !this.config.is_mobile &&
( screenWidth < this.config.width_threshold || screenHeight < this.config.height_threshold );

return isNotValidForMobile || isNotValidForDesktop;
}

_generateLcpCandidates( count ) {
const lcpElements = document.querySelectorAll( this.config.elements );

if ( lcpElements.length <= 0 ) {
return [];
}

const potentialCandidates = Array.from( lcpElements );

const topCandidates = potentialCandidates.map(element => {
const rect = element.getBoundingClientRect();
return {
element: element,
rect: rect,
};
}).filter(item => {
return (
item.rect.width > 0 &&
item.rect.height > 0 &&
this._isIntersecting(item.rect)
);
})
.map(item => ({
item,
area: this._getElementArea(item.rect),
elementInfo: this._getElementInfo(item.element),
}))
.sort((a, b) => b.area - a.area)
.slice(0, count);

return topCandidates.map(candidate => ({
element: candidate.item.element,
elementInfo: candidate.elementInfo,
}));
}

_isIntersecting(rect) {
// Check if any part of the image is within the viewport
return (
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.left <= (window.innerWidth || document.documentElement.clientWidth)
);
}

_getElementArea(rect) {
const visibleWidth = Math.min(rect.width, (window.innerWidth || document.documentElement.clientWidth) - rect.left);
const visibleHeight = Math.min(rect.height, (window.innerHeight || document.documentElement.clientHeight) - rect.top);

return visibleWidth * visibleHeight;
}

_getElementInfo(element) {
const nodeName = element.nodeName.toLowerCase();
const element_info = {
type: "",
src: "",
srcset: "",
sizes: "",
sources: [],
bg_set: [],
current_src: ""
};

const css_bg_url_rgx = /url\(\s*?['"]?\s*?(\S+?)\s*?["']?\s*?\)\s*?([a-zA-Z0-9\s]*[x|dpcm|dpi|dppx]?)/ig;

if (nodeName === "img" && element.srcset) {
element_info.type = "img-srcset";
element_info.src = element.src;
element_info.srcset = element.srcset; // capture srcset
element_info.sizes = element.sizes; // capture sizes
element_info.current_src = element.currentSrc;
} else if (nodeName === "img") {
element_info.type = "img";
element_info.src = element.src;
element_info.current_src = element.currentSrc;
} else if (nodeName === "video") {
element_info.type = "img";
const source = element.querySelector('source');
element_info.src = element.poster || (source ? source.src : '');
element_info.current_src = element_info.src;
} else if (nodeName === "svg") {
const imageElement = element.querySelector('image');
if (imageElement) {
element_info.type = "img";
element_info.src = imageElement.getAttribute('href') || '';
element_info.current_src = element_info.src;
}
} else if (nodeName === "picture") {
element_info.type = "picture";
const img = element.querySelector('img:not(picture>img)');
element_info.src = img ? img.src : "";
element_info.sources = Array.from(element.querySelectorAll('source')).map(source => ({
srcset: source.srcset || '',
media: source.media || ''
}));
} else {
const computed_style = window.getComputedStyle(element, null);
const bg_props = [
computed_style.getPropertyValue("background-image"),
getComputedStyle(element, ":after").getPropertyValue("background-image"),
getComputedStyle(element, ":before").getPropertyValue("background-image")
];

const full_bg_prop = bg_props.filter(prop => prop !== "none").join("");
element_info.type = "bg-img";
if (full_bg_prop.includes("image-set(")) {
element_info.type = "bg-img-set";
}
if (!full_bg_prop || full_bg_prop === "") {
return null;
}

const matches = [...full_bg_prop.matchAll(css_bg_url_rgx)];
element_info.bg_set = matches.map(m => m[1] ? {src: m[1].trim() + (m[2] ? " " + m[2].trim() : "")} : {});
// Check if bg_set array is populated with empty objects
if (element_info.bg_set.every(item => item.src === "")) {
// If bg_set array is populated with empty objects, populate it with the URLs from the matches array
element_info.bg_set = matches.map(m => m[1] ? {src: m[1].trim()} : {});
}

if (element_info.bg_set.length > 0) {
element_info.src = element_info.bg_set[0].src;
if (element_info.type === "bg-img-set") {
element_info.src = element_info.bg_set;
}
}
}

return element_info;
}

_initWithFirstElementWithInfo(elements) {
const firstElementWithInfo = elements.find(item => item.elementInfo !== null);

if ( ! firstElementWithInfo ) {
this._logMessage("No LCP candidate found.");
this.performanceImages = [];
return;
}

this.performanceImages = [{
...firstElementWithInfo.elementInfo,
label: "lcp",
}];
}

_fillATFWithoutDuplications(elements) {
elements.forEach(({ element, elementInfo }) => {
if ( this._isDuplicateImage(element) ) {
return;
}

this.performanceImages.push({ ...elementInfo, label: "above-the-fold" });
});
}

_isDuplicateImage(image) {
const elementInfo = this._getElementInfo(image);

if (elementInfo === null) {
return false;
}

const isImageOrVideo =
elementInfo.type === "img" ||
elementInfo.type === "img-srcset" ||
elementInfo.type === "video";

const isBgImageOrPicture =
elementInfo.type === "bg-img" ||
elementInfo.type === "bg-img-set" ||
elementInfo.type === "picture";

return (isImageOrVideo || isBgImageOrPicture)
&&
this.performanceImages.some(item => item.src === elementInfo.src);
}

_saveFinalResultIntoDB() {
if ( ! this.performanceImages ) {
return;
}

const data = new FormData();
data.append('action', 'rocket_lcp');
data.append('rocket_lcp_nonce', this.config.nonce);
data.append('url', this.config.url);
data.append('is_mobile', this.config.is_mobile);
data.append('images', JSON.stringify(this.performanceImages));
data.append('status', 'success');

fetch(rocket_lcp_data.ajax_url, {
method: "POST",
credentials: 'same-origin',
body: data,
headers: {
'wpr-saas-no-intercept': true
}
})
.then((response) => response.json())
.then((data) => {
this._logMessage(data);
})
.catch((error) => {
this._logMessage(error);
})
.finally(() => {
this._finalize();
});
}

_finalize() {
const beaconscript = document.querySelector('[data-name="wpr-lcp-beacon"]');
beaconscript.setAttribute('beacon-completed', 'true');
}

_logMessage( msg ) {
if ( ! this.config.debug ) {
return;
}
console.log( msg );
}

static run() {
if ( !window.rocket_lcp_data ) {
return;
}

const instance = new RocketLcpBeacon( window.rocket_lcp_data );

if (document.readyState !== 'loading') {
setTimeout(() => {
instance.init();
}, 500);
return;
}

document.addEventListener("DOMContentLoaded", () => {
setTimeout(() => {
instance.init();
}, 500);
});
}
}

RocketLcpBeacon.run();
1 change: 1 addition & 0 deletions assets/js/lcp-beacon.js.min.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions assets/js/lcp-beacon.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading