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

Script Modules API: Move the script modules to the footer in classic themes #1

Conversation

luisherranz
Copy link
Owner

@luisherranz luisherranz commented Jan 16, 2024

Trac ticket: https://core.trac.wordpress.org/ticket/60240


!! This is built on top of WordPress#5869. For that reason it's still a local PR. I will rebase it and open a PR in the WordPress/wordpress-develop once WordPress#5869 is merged.

What

Moves the script module prints to the footer in classic themes. It also removes the ability to call the print functions more than once because it's now unnecessary.

Why

In the ticket that introduced the Script Modules API (#56313), I added a logic that prints as many enqueued and preloads as possible in the head, then prints the remaining ones in the footer and includes the import map. I explain my reasoning ​in this comment.

But @cbravobernal realized that import maps fail if they appear after the modules. That means that there's no other way but printing the import map first, and then all the modules and preloads (yes, preloads also fail!). So we need to check if we are on a classic or block theme, and if we are in a classic theme, move everything to the footer.

How

By leveraging wp_is_block_theme() and moving everything to the footer in classic themes:

public function add_hooks() {
  $position = wp_is_block_theme() ? 'wp_head' : 'wp_footer';
  add_action( $position, array( $this, 'print_import_map' ) );
  add_action( $position, array( $this, 'print_enqueued_modules' ) );
  add_action( $position, array( $this, 'print_module_preloads' ) );
}

Additional comments

@westonruter mentioned that we could optimize this in the future if we have a way to filter the output before sending the response to the client:

@luisherranz luisherranz changed the title Script Modules API: Move the modules to the footer in classic themes Script Modules API: Move the script modules to the footer in classic themes Jan 16, 2024
@luisherranz luisherranz force-pushed the fix-import-map-load-in-classic-themes branch from 7d48527 to 0871981 Compare January 17, 2024 12:15
@luisherranz luisherranz force-pushed the fix-import-map-load-in-classic-themes branch from 0871981 to a7eaf39 Compare January 18, 2024 07:28
@luisherranz luisherranz force-pushed the rename-module-functions-to-script-modules branch from 9f1af46 to c1a6909 Compare January 23, 2024 10:00
@luisherranz
Copy link
Owner Author

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.

1 participant