[wp-trac] [WordPress Trac] #51325: Add a filter for script/style tags injected by wp_add_inline_{script|style}

WordPress Trac noreply at wordpress.org
Tue Feb 9 20:11:11 UTC 2021


#51325: Add a filter for script/style tags injected by wp_add_inline_{script|style}
---------------------------+------------------------------
 Reporter:  pjohanneson    |       Owner:  (none)
     Type:  enhancement    |      Status:  new
 Priority:  normal         |   Milestone:  Awaiting Review
Component:  Script Loader  |     Version:
 Severity:  normal         |  Resolution:
 Keywords:                 |     Focuses:
---------------------------+------------------------------

Comment (by GeekPress):

 Hi there 🤚

 I've added a patch to add 3 new hooks:
 - `inline_script_before_loader_tag`

 - `inline_script_after_loader_tag`

 - `inline_style_loader_tag`

 I have voluntarily added the hooks before to be printed into the `do_item`
 functions.

 Why?
 We would be able to make some updates on the script/style tag AND the
 content.

 Here some usages of the hooks:

 **1. Add a custom attribute on the inline script tag**

 {{{
 function do_not_optimize_jquery_inline_scripts( $before_handle_tag,
 $handle ) {
         if ( 'jquery-core' === $handle ) {
                 $before_handle_tag = str_replace( '<script', '<script
 data-no-optimize="1"', $before_handle_tag );
         }
         return $before_handle_tag;
 }
 add_filter( 'inline_script_before_loader_tag',
 'do_not_optimize_jquery_inline_scripts', 10, 2 );
 }}}

 **2- Wrap the content of the inline scripts:**
 {{{
 function fix_jquery_render_blocking_inline_scripts( $before_handle_tag,
 $handle ) {
         if ( 'jquery-core' === $handle ) {
                 $before_handle_tag = preg_replace(
                         '#<script.*>(.*)</script>#Usmi',
                         'window.addEventListener(\'DOMContentLoaded\',
 function() {$1});',
                         $before_handle_tag
                 );
         }
         return $before_handle_tag;
 }
 add_filter( 'inline_script_before_loader_tag',
 'fix_jquery_render_blocking_inline_scripts', 10, 2 );
 }}}

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


More information about the wp-trac mailing list