-
Notifications
You must be signed in to change notification settings - Fork 0
Load Block Scripts Only When Used via wp_register_script #123
Description
Ensure that all frontend scripts in the Frontblocks plugin are only loaded when their corresponding blocks are used, by properly registering scripts with wp_register_script and enqueueing them conditionally both in PHP and block definitions.
Problem
Currently, scripts may be globally enqueued regardless of whether the associated blocks are present on the page. This leads to unnecessary asset loading, negatively impacting performance, page speed, and overall user experience.
Goal
Load scripts only when their respective blocks are rendered on the page by leveraging WordPress best practices for script registration and conditional enqueueing.
Scope / Features
- Refactor script handling to use wp_register_script instead of direct enqueueing
- Conditionally enqueue scripts only when blocks are present on the page
- Ensure compatibility with both:
- PHP-rendered blocks
- JavaScript block registration (block.json or registerBlockType)
- Support frontend and editor contexts where needed
- Maintain dependency management and versioning
Non-Goals
- No redesign of existing blocks
- No changes to styling unless required for script dependencies
- No migration to external build tools or frameworks
User Stories
As a site visitor, I want pages to load only necessary scripts so that performance is optimized.
As a developer, I want scripts to be conditionally loaded per block so that I follow WordPress best practices.
Flow
-
Register all block-related scripts using wp_register_script during init
-
Associate registered scripts with blocks via:
- block.json (using "script" or "viewScript")
- or render_callback in PHP
-
Detect block usage:
- Automatic via block.json
- Or manual check in PHP render functions
-
Enqueue scripts only when the block is rendered on the page
-
Ensure scripts are not globally enqueued elsewhere
Technical Notes
-
Use wp_register_script with proper dependencies and versioning
-
Prefer block.json fields:
- "script"
- "viewScript"
-
For dynamic blocks, enqueue inside render_callback
-
Consider using has_block() for conditional checks in edge scenarios
-
Ensure scripts are not duplicated between editor and frontend
Edge Cases
- Blocks rendered via reusable blocks or patterns
- Blocks inside widgets or template parts
- Server-side rendered blocks where detection may differ
- Multiple instances of the same block on a page
- Caching plugins affecting script loading behavior
Acceptance Criteria
- Scripts are not loaded globally across all pages
- Scripts are loaded only when their corresponding block is present
- No regression in block functionality
- Editor scripts continue to function correctly
- No duplicate script loading occurs