Skip to content

Count script dependencies toward the enqueued size total (#74) - #1488

Open
gunjanjaswal wants to merge 8 commits into
WordPress:trunkfrom
gunjanjaswal:fix/74-count-script-dependencies
Open

gunjanjaswal wants to merge 8 commits into
WordPress:trunkfrom
gunjanjaswal:fix/74-count-script-dependencies

Conversation

@gunjanjaswal

@gunjanjaswal gunjanjaswal commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What?

Enqueued_Scripts_Size_Check now counts a plugin script's dependencies toward the cumulative page size, not just the scripts served from the plugin's own directory.

Fixes #74

Why?

The check only measured scripts whose src started with the plugin's own URL. Anything a plugin script depends on but that's served from elsewhere, jQuery being the obvious one, was skipped entirely, even though it loads on the page because the plugin enqueued something that needs it. That undercounts the real weight the plugin adds to a page.

How?

  • For each of the plugin's enqueued scripts, walk its dependency graph (->deps, transitively, de-duplicated) and add every dependency's size to the page total.
  • Resolve each handle's src to a local file with a load_script_textdomain-style mapper that understands the plugin directory, wp-content, wp-includes, and the site root (including root-relative and protocol-relative srcs). Scripts served from another host, such as a CDN, can't be measured locally, so they're skipped rather than guessed at.
  • Warnings still point only at the plugin's own files, since those are what the author controls; dependencies just contribute to the total that trips the threshold.

I kept this scoped to the scripts check to keep the diff reviewable. Enqueued_Styles_Size_Check has the same shape and the same gap, so I'm happy to follow up by converging the two into a shared base (as you suggested in the issue) and applying the dependency accounting there too, either in this PR or a separate one, whichever you prefer.

AI Usage Disclosure

  • This PR includes AI-assisted code or content

AI assistance (Claude Code) was used to explore the check and draft the dependency-walking and URL-to-path logic and the test. I reviewed the change, ran the check's PHPUnit tests and PHPCS locally, and take responsibility for what's here.

Testing Instructions

  1. Build a plugin that enqueues a script which declares a dependency served from outside the plugin, e.g. wp_enqueue_script( 'my-script', plugins_url( 'my-script.js', __FILE__ ), array( 'jquery' ) ).
  2. Run Plugin Check's performance checks with a script-size threshold below the combined size of your script plus jQuery, but above your script alone.
  3. Before this change the check stays quiet (jQuery isn't counted); after it, the cumulative total includes the dependency and the threshold warning fires.

Automated: the new test_run_counts_external_dependencies case in Enqueued_Scripts_Size_Check_Tests.php sets a threshold between the plugin script's own size and its size once a dependency is included, and asserts the warning only appears because the dependency is counted.

Open WordPress Playground Preview

Enqueued_Scripts_Size_Check only measured scripts whose src started with
the plugin's own URL, so any dependency served from elsewhere (jQuery, a
shared vendor library) was ignored even though it loads because of the
plugin and adds to the page weight.

Walk each plugin script's dependency graph, de-duplicated, and resolve
every handle's src to a local file with a load_script_textdomain-style
mapper (plugin dir, wp-content, wp-includes, site root). Dependencies
count toward the page total; scripts served from another host, such as a
CDN, are skipped since their size can't be read locally. Warnings still
point only at the plugin's own files.

Fixes WordPress#74.
@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: gunjanjaswal <gunjanjaswal@git.wordpress.org>
Co-authored-by: ernilambar <nilambar@git.wordpress.org>
Co-authored-by: swissspidy <swissspidy@git.wordpress.org>
Co-authored-by: jjgrainger <joegrainger@git.wordpress.org>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub or WordPress.org user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Inline dependency payloads remain undercounted, and the required dependency-size reporting is missing.

Review effort: Balanced
Findings: 3 Medium severity · 1 Low severity

Open (4)
What changed in this PR

Updates the runtime script-size check to include measurable dependencies in cumulative page weight.

Changes:

  • Traverses and de-duplicates script dependencies.
  • Maps local script URLs to filesystem paths.
  • Adds an uploads-based dependency fixture and PHPUnit coverage.
File Description
includes/​Checker/​Checks/​Performance/​Enqueued_Scripts_Size_Check.php Adds dependency traversal, path resolution, and size accounting.
tests/​phpunit/​tests/​Checker/​Checks/​Enqueued_Scripts_Size_Check_Tests.php Tests direct external dependency accounting.
tests/​phpunit/​testdata/​plugins/​test-plugin-enqueued-script-size-check/​load.php Registers the external dependency fixture.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines 250 to 254
/* translators: 1: script file size. 2: tested URL. 3: threshold file size. */
__( 'This script has a size of %1$s which in combination with the other scripts enqueued on %2$s exceeds the script size threshold of %3$s.', 'plugin-check' ),
size_format( $plugin_script['size'] ),
size_format( $measured[ $handle ]['size'] ),
$url,
size_format( $this->threshold_size )
Comment on lines +12 to +16
$uploads = wp_upload_dir();
$dep_file = trailingslashit( $uploads['basedir'] ) . 'plugin-check-external-dependency.js';

if ( ! file_exists( $dep_file ) ) {
file_put_contents( $dep_file, str_repeat( 'a', 1000 ) );
Comment on lines +119 to +123
public function test_run_counts_external_dependencies() {
// Load the test plugin, whose script depends on a 1000 byte script served from outside
// the plugin directory.
require UNIT_TESTS_PLUGIN_DIR . 'test-plugin-enqueued-script-size-check/load.php';

- Use ABSPATH . 'wp-includes/' instead of the WPINC constant, which the
  PHPStan config doesn't have stubbed.
- Count a dependency's inline before/after code even when its file can't
  be resolved locally (e.g. a CDN script); WordPress still prints it.
- Exercise a transitive dependency and a remote (skipped) dependency in
  the fixture, and clean up the fixture's uploads files on tear down.
@gunjanjaswal

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Pushed b9cf12b to address it:

  • Inline payload on unresolvable deps — good catch. When a dependency's file can't be resolved (a CDN script, say), the inline before/after code is still printed, so it's now counted regardless of whether the file itself is measurable.
  • PHPStan — the CI failure was Constant WPINC not found, since it isn't stubbed here. Switched to ABSPATH . 'wp-includes/'.
  • Fixture cleanup — the uploads files the fixture writes are now removed on tear_down().
  • Test coverage — the fixture now also exercises a transitive dependency (the direct dep depends on a second file) and a remote dependency that can't be measured locally and is skipped. The dependency test's threshold sits between the size with only the direct dep and the size once the transitive one is included, so recursive traversal is actually asserted.

On the suggestion to track plugin vs dependency sizes separately and report both in the warning: I read #74 as asking for dependencies to be counted "as part of the total script size for a page load," which is what this does, rather than a change to what the warning reports. Happy to add a separate dependency breakdown if a maintainer wants it, but I left the warning format as-is to keep the change focused.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The warning omits the separate dependency and total-size reporting required by issue #74.

Review effort: Balanced
Findings: 2 Medium severity · 2 Low severity

Open (4)
Resolved since last review (1)

public function test_run_counts_external_dependencies() {
// The fixture's script depends on a 1000 byte script served from the uploads directory,
// which in turn depends on a 500 byte transitive one, plus a remote (CDN) script that
// can't be measured locally and must be skipped rather than fataling.
@gunjanjaswal

Copy link
Copy Markdown
Contributor Author

Thanks for running the review again, @ernilambar. Quick status on where things stand after the latest push (3e35f29): CI is green, and the re-review cleared three of the four findings — the inline payload is now counted even when a dependency's file can't be resolved, the fixture cleans up its uploads files on tear down, and the fixture/tests now exercise a transitive dependency and a remote (CDN) skip, with the threshold sitting between the direct-only and transitive totals so the recursive traversal is actually asserted.

The one remaining item is the suggestion to report the dependency contribution separately in the warning. I read #74 as asking for dependencies to count toward the total (which they now do) rather than a change to the message, so I left the wording alone. That said, I'm happy to add a breakdown if you'd find it useful for triage, something like:

This script has a size of 40 KB which in combination with the other scripts enqueued on {URL} exceeds the script size threshold of 300 KB. Dependencies account for 180 KB of the total.

Want me to add that line (shown only when dependencies actually contribute), or keep the message as-is? Happy to go whichever way you prefer.

@gunjanjaswal

Copy link
Copy Markdown
Contributor Author

Circling back on this, @ernilambar. After the last re-review three of the four findings were cleared and CI's still green, so it feels close. Is there anything outstanding on the remaining point, or anything else you'd like changed before it can move forward? Happy to jump on it.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

foreach ( $roots as $root ) {
list( $url_root, $dir_root ) = $root;

if ( ! $url_root || strpos( $src, $url_root ) !== 0 ) {
A same-host dependency can be served over https while the site's URL
roots (plugins_url, content_url, includes_url, site_url) are registered
over http. The prefix match in get_local_path_from_roots() was
scheme-sensitive, so such a dependency failed every root check and had
its size silently counted as zero, which could suppress the enqueued
size-threshold warning.

Normalize both the source and each URL root to a single scheme before
the prefix comparison, keeping the host and path checks intact. Adds a
test covering an https dependency against http roots.
Issue WordPress#74 asks for the dependency total to be reported distinctly from
the plugin's own enqueued scripts. The warning now states the combined
size of the plugin's scripts and the additional weight their
dependencies add, instead of folding everything into a single figure.

Also replaces a non-standard 'fataling' in a test comment.
@gunjanjaswal

Copy link
Copy Markdown
Contributor Author

Pushed two changes.

The scheme-sensitive matching is fixed. get_local_path_from_roots() now normalizes both the dependency src and each URL root to a single scheme before the prefix check, so a dependency served over https still resolves against http URL roots (and the other way round) instead of being silently counted as zero. Added a test that resolves an https dependency against the http content root.

I also split the reporting to line up with the acceptance criteria on #74: the warning now gives the plugin's own enqueued-script total and the dependency contribution as separate figures, rather than folding everything into one number.

Minor cleanup too, dropped the non-standard "fataling" in the transitive-dependency test comment. The older note about the fixture file lingering in uploads is already covered, the test's tear_down() removes the files it writes.

The size check resolves dependency srcs served root-relative (core's
/wp-includes/... scripts) and protocol-relative (//host/path), but only
fully-qualified and scheme-mismatched srcs were exercised. Add a test
for both branches of get_path_from_src so a regression that counts a
core dependency as zero bytes is caught.
@gunjanjaswal

Copy link
Copy Markdown
Contributor Author

Gentle nudge on this one. It's been green for a few weeks and is just waiting on a first maintainer look. It teaches the enqueued-scripts size check to count a script's dependencies toward the page total (per #74), reporting the plugin's own weight and the dependency weight separately. Happy to adjust anything if there's a preference on the message wording or the threshold handling.

@ernilambar

Copy link
Copy Markdown
Member

Summary

Counts each plugin script's dependencies (transitive and de-duplicated, including core ones like jQuery) toward the page's total script size, and reports the plugin's own size and the dependency size as separate numbers. This meets the main requirement of #74. CI, PHPCS and PHPStan all pass. Still to fix: the @since tags are wrong, the new warning text is misleading, and no test checks the plugin/dependency split that the issue asks for.

✅ What's good

  • The dependency walk (get_handle_with_dependencies()) is recursive and de-duplicated through a shared $seen map, so a dependency shared by several plugin scripts is counted once.
  • When a dependency's file can't be found (CDN, src set to false for aliases like jquery), its inline before/after code is still counted. This is correct, because WordPress prints that code either way.
  • Root-relative src values are resolved with site_url(), the same way WP_Scripts::do_item() builds them, so core scripts work when WordPress is installed in a subdirectory.
  • Warnings are still raised only for the plugin's own files. This avoids flagging files the author doesn't control.
  • Fixes the old translator comment, which said "style file size" in the scripts check.
  • The scheme normalization fixes a real case: an https dependency on a site whose URL roots are http would otherwise count as 0 bytes.

⚠️ Must-fix before merge

  • includes/Checker/Checks/Performance/Enqueued_Scripts_Size_Check.php:281 — @since 1.6.0 on every new method (lines 281, 309, 347, 388, 402) is wrong. The plugin is at 2.2.0, so these methods are being added in the next release, not in 1.6.0. Change them to the next release version.
  • includes/Checker/Checks/Performance/Enqueued_Scripts_Size_Check.php:264 — "The scripts enqueued on %2$s total %3$s" says all scripts on the page total %3$s, but %3$s is only the plugin's own scripts ($plugin_size). Readers will misread it. The message also never states the combined total that was actually compared to the threshold, so the reader has to add the two numbers. And when nothing comes from dependencies, it prints "dependencies adding a further 0 B". Suggested fix:
    • Say "the plugin's scripts" explicitly.
    • Show the combined total.
    • Use a shorter message without the dependency clause when $dependency_size === 0.
  • tests/phpunit/tests/Checker/Checks/Enqueued_Scripts_Size_Check_Tests.php:131 — test_run_counts_external_dependencies() checks only that there are 4 warnings. The issue's acceptance criteria require dependency sizes to be tracked and reported separately, and nothing tests that. Assert the warning message, or at least that it contains the expected plugin size and dependency size (~53 B / 1,500 B). A bug in the subtraction at lines 245–251 would currently pass CI.

💡 Suggestions (optional)

  • includes/Checker/Checks/Performance/Enqueued_Scripts_Size_Check.php:354 — plugins_url() and content_url() have no trailing slash, so the prefix check also matches siblings. For example, …/wp-content-cache/x.js matches content_url() and maps to WP_CONTENT_DIR . '-cache/x.js'. Line 380 also returns false on the first prefix match without trying the remaining roots (such as site_url( '/' )). Use trailingslashit() on both the URL and directory roots, and continue instead of return false when the file doesn't exist.
  • includes/Checker/Checks/Performance/Enqueued_Scripts_Size_Check.php:331 — The is_ssl() branch has no effect, because get_local_path_from_roots() changes the scheme to https anyway. Prefixing 'https:' is enough.
  • includes/Checker/Checks/Performance/Enqueued_Scripts_Size_Check.php:395 — The minimum WordPress version is 6.3, so wp_filesize() always exists and the function_exists() fallback is dead code. wp_filesize() also always returns an int, so the is_int() ternary does nothing. This could be return wp_filesize( $path );.
  • includes/Checker/Checks/Performance/Enqueued_Scripts_Size_Check.php:222 — Design point to agree on: dependencies are charged to the plugin even when the theme or core would load them anyway (for example, a theme that already enqueues jQuery). A plugin with a frontend script that depends on wp-components will now go over 300 KB on its own. That may well be the intended effect of a performance check, but maintainers should confirm the behaviour change before release, since some plugins will start getting warnings they didn't get before.
  • tests/phpunit/testdata/plugins/test-plugin-enqueued-script-size-check/load.php:20 — The fixture now adds about 1.5 KB of dependencies for every test that loads it. The low-threshold tests (( 1 ) and ( 20 ) at lines 98 and 117) now pass because of the dependencies rather than the plugin's own script or inline code, so they no longer test what their names describe. Register the dependencies in a separate fixture, or only in the dependency test. Also, writing files inside a wp_enqueue_scripts callback is an odd side effect; create them in set_up() instead.
  • tests/phpunit/tests/Checker/Checks/Enqueued_Scripts_Size_Check_Tests.php:131 — Missing test: two plugin scripts that share one dependency, to show it is counted once.
  • Scope — The maintainer comment on Enqueued_Scripts_Size_Check includes script dependencies #74 suggests first converging this check with Enqueued_Styles_Size_Check through a shared base class or trait. This PR doesn't do that, so the styles check still has the same gap and the two checks are now inconsistent. Open a follow-up issue now so it gets tracked.

Verdict

Request Changes — The approach is sound and meets #74's intent, but the warning text misstates what it measures, the @since tags are wrong, and the separate reporting the issue asks for has no test.

The warning text said it counted the scripts enqueued on a URL when it
actually measures this plugin's own scripts and the dependencies they
pull in, so reword it to say that and spell out the combined total. Drop
the dependency clause when a script has no measurable dependencies.

Correct the @SInCE tags on the helpers added for dependency counting to
the upcoming release, and add a test that asserts the plugin size, the
dependency size and the combined total are each reported, so a
regression in the plugin/dependency split is caught instead of passing
on the warning count alone.
@gunjanjaswal

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @ernilambar. Pushed 021d428 with the three must-fixes.

@since tags. Fixed. I went with 2.3.0 rather than 2.2.0, since trunk already carries a batch of @since 2.3.0 tags, so that reads as the current dev target. Let me know if it should be something else.

Warning text. Reworded to: "The scripts from this plugin on %s total %s, and their dependencies add a further %s, for a combined %s, which exceeds the script size threshold of %s." That labels the plugin figure as the plugin's own, states the combined total outright, and there's a shorter variant without the dependency clause when $dependency_size is 0, so no more "a further 0 B".

Test for the split. test_run_counts_external_dependencies() now asserts the warning reports the plugin size, the dependency size, and the combined total, each in its own position in the sentence. A bad subtraction changes one of those numbers and fails the test instead of passing on the warning count alone.

Optionals:

  • Trailing slashes and the early return: both the URL and directory roots get trailingslashit() now, and resolution continues to the next root instead of returning false on the first prefix match, so an overlapping root like site_url() still gets a chance to resolve the file.
  • is_ssl() branch: dropped. It just prefixes https: now, since the root matching normalizes the scheme anyway.
  • wp_filesize(): collapsed to return wp_filesize( $path );. You're right that the function_exists() fallback and the int cast are both dead on 6.3+.
  • Charging core/theme deps to the plugin: I read this as the intended effect of a performance check, but it is a behaviour change, so I've left it as-is and flagged it here for a maintainer call before release rather than deciding it myself.
  • Styles check: opened Share dependency-size logic between the enqueued scripts and styles checks #1557 to track converging the two checks behind a shared base or trait, which also closes the same dependency gap on the styles side.
  • Fixture split and the shared-dependency test: I've left these for a follow-up rather than fold them in here. Splitting the dependency fixture out so the low-threshold tests stop leaning on it means reworking the shared setup, and I'd rather do that as its own focused change than pile more test churn into this PR. Glad to roll both in here instead if you'd prefer them together.

… limit

Reporting the plugin and dependency sizes separately pushed check_url()
past PHPMD's 100-line method limit. Move the message building into a
small helper so the method stays within it; the message text is
unchanged.
@gunjanjaswal

Copy link
Copy Markdown
Contributor Author

Thanks @ernilambar, appreciate you going through this so carefully across the rounds. #1557 is open for the scripts/styles convergence whenever that's worth picking up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enqueued_Scripts_Size_Check includes script dependencies

3 participants