[wp-trac] [WordPress Trac] #54018: Allow scripts registered via block.json to be enqueued in the footer

WordPress Trac noreply at wordpress.org
Tue Mar 21 12:28:21 UTC 2023


#54018: Allow scripts registered via block.json to be enqueued in the footer
---------------------------+------------------------------
 Reporter:  jeremyfelt     |       Owner:  (none)
     Type:  enhancement    |      Status:  new
 Priority:  normal         |   Milestone:  Awaiting Review
Component:  Script Loader  |     Version:
 Severity:  normal         |  Resolution:
 Keywords:  has-patch      |     Focuses:  performance
---------------------------+------------------------------

Comment (by belbo):

 @gziolo is this still the best way of doing this? I tried your suggestion
 of passing an already registered script handle, which worked but then WP
 scripts no-longer compiles the script I wanted to include.

 For anyone else looking for a solution this is how to do it (unless
 @gziolo comes back with a better way as this ticket is quite old, however
 it is the first to show up on Google!)

 In block.json


 {
         "$schema": "https://schemas.wp.org/trunk/block.json",
         "apiVersion": 2,
         "name": "prefix/blockname"
         ...
         "viewScript": [ "carousel-fe", "file:./carousel.js" ] //enqueue
 the same file twice
 }


 in functions.php


 {{{
 function enqueue_fe_scripts() {

         // Dequeue script loaded by gutenberg so script not added twice
         wp_dequeue_script( 'prefix-blockname-view-script-2' );

         // include build script so can get dependencies, build version etc
         $carousel_asset = include PATH_TO_FILE . '/index.asset.php';

         // Register but don't enqueue the script, as Gutenberg will
 enqueue it through viewScript
         wp_register_script(
                 'carousel-fe',
                 PATH_TO_FILE_URI/carousel.js,
                 array(),
                 $carousel_asset['version'],
                 true
         );
 }

 add_action( 'wp_enqueue_scripts', 'enqueue_fe_scripts', 30 );
 }}}


 As far as I can tell this is the only way of getting WP scripts to compile
 the file to include on the Front End AND include it in the footer.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/54018#comment:8>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list