[wp-trac] [WordPress Trac] #22249: Add ability to set or remove attributes on enqueued scripts and styles.

WordPress Trac noreply at wordpress.org
Sun Oct 21 23:29:14 UTC 2012


#22249: Add ability to set or remove attributes on enqueued scripts and styles.
-----------------------------+-----------------------------
 Reporter:  ryanve           |       Type:  feature request
   Status:  new              |   Priority:  normal
Milestone:  Awaiting Review  |  Component:  General
  Version:                   |   Severity:  normal
 Keywords:  dev-feedback     |
-----------------------------+-----------------------------
 I think it should be easier to customize the loading of scripts and styles
 (easier to customize the markup generated by the script/style system).
 Proposed solutions:

 '''Solution 1:''' Allow `wp_enqueue_script`, `wp_enqueue_style`,
 `wp_register_script`, `wp_register_style` to accept an array of attributes
 as the `$src` parameter. For example:

 {{{
 wp_enqueue_script( 'my-plugin', array(
     'src' => 'http://example.com/js/app.js'
     'defer' => ''
     'data-my-plugin' => 'custom data attr value'
 ), array('jquery'), null, true );
 }}}

 '''Solution 2:''' Add a filter before the markup is generated that allows
 devs to filter the attributes while they are in array format. For example:

 {{{
 add_filter('script_loader_attrs', function ($attrs, $handle) {
     unset ( $attrs['type'] );
     'my-plugin' === $handle and $attrs['data-my-plugin'] = 'plugin data';
     $attrs['src'] = remove_query_arg( $attrs['src'] );
     return $attrs;
 }, 12, 2);
 }}}
 In class.wp-scripts.php it might look something like:

 {{{
 $attrs = (array) apply_filters('script_loader_attrs', $attrs, $handle);
 }}}

 and/or:

 {{{
 $attrs = (array) apply_filters("{$handle}_script_loader_attrs", $attrs );
 }}}

 ----

 I imagine that solution '''2''' would be easier to implement than '''1''',
 and '''2''' allows for themes/plugins to modify scripts/styles w/o re-
 registering resources.

 The key feature of both solutions is the ability to modify the attrs while
 in array format. There are other ways that one could achieve the same
 results, but the array is '''by far the cleanest'''. Dirty alternatives
 include:
 * Use `preg_replace()` on the markup after it is generated (see #22245)
 * Use output buffers and PHP's DOMElement interface
 * Filter away the "print_scripts_array" and regenerate the
 markupmanually.)

-- 
Ticket URL: <http://core.trac.wordpress.org/ticket/22249>
WordPress Trac <http://core.trac.wordpress.org/>
WordPress blogging software


More information about the wp-trac mailing list