[wp-trac] [WordPress Trac] #22249: Add ability to set or remove attributes on enqueued scripts and styles.
WordPress Trac
noreply at wordpress.org
Fri Jun 27 01:40:24 UTC 2014
#22249: Add ability to set or remove attributes on enqueued scripts and styles.
-----------------------------+------------------------------
Reporter: ryanve | Owner:
Type: feature request | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Script Loader | Version:
Severity: normal | Resolution:
Keywords: dev-feedback | Focuses:
-----------------------------+------------------------------
Comment (by jphase):
Replying to [ticket:22249 ryanve]:
> 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 );
> }}}
>
I think '''Solution 1''' makes complete sense from a developer's
standpoint. This solution could keep any previous filters intact and
provide a simple type check on the second param to change the way this is
rendered. I'd be happy to help submit a diff for this or #23236 if any
help is needed.
> '''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: <https://core.trac.wordpress.org/ticket/22249#comment:10>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list