[wp-trac] [WordPress Trac] #12009: Add support for HTML 5 "async" and "defer" attributes
WordPress Trac
noreply at wordpress.org
Fri Mar 9 17:13:45 UTC 2018
#12009: Add support for HTML 5 "async" and "defer" attributes
---------------------------+-----------------------------
Reporter: Otto42 | Owner: azaozz
Type: enhancement | Status: reopened
Priority: normal | Milestone: Future Release
Component: Script Loader | Version: 4.6
Severity: normal | Resolution:
Keywords: | Focuses:
---------------------------+-----------------------------
Comment (by westonruter):
@ocean90 here's a(nother) plugin implementation (and polyfill) for what
you describe:
{{{#!php
<?php
/**
* Add async/defer attributes to enqueued scripts that have the specified
script_execution flag.
*
* @link https://core.trac.wordpress.org/ticket/12009
* @param string $tag The script tag.
* @param string $handle The script handle.
* @return string
*/
function wp12009_filter_script_loader_tag( $tag, $handle ) {
$script_execution = wp_scripts()->get_data( $handle,
'script_execution' );
if ( ! $script_execution ) {
return $tag;
}
if ( 'async' !== $script_execution && 'defer' !==
$script_execution ) {
return $tag; // _doing_it_wrong()?
}
// Abort adding async/defer for scripts that have this script as a
dependency. _doing_it_wrong()?
foreach ( wp_scripts()->registered as $script ) {
if ( in_array( $handle, $script->deps, true ) ) {
return $tag;
}
}
// Add the attribute if it hasn't already been added.
if ( ! preg_match( ":\s$script_execution(=|>|\s):", $tag ) ) {
$tag = preg_replace( ':(?=></script>):', "
$script_execution", $tag, 1 );
}
return $tag;
}
add_filter( 'script_loader_tag', 'wp12009_filter_script_loader_tag', 10, 2
);
}}}
Then to make `comment-reply.js` async all that is needed is as you showed
and @georgestephanis suggested:
{{{#!php
<?php
add_action( 'wp_enqueue_scripts', function() {
wp_script_add_data( 'comment-reply', 'script_execution', 'async'
);
} );
}}}
I like not using a boolean attribute, but the `script_execution` name
doesn't feel quite right yet.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/12009#comment:57>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list