We should have a way of registering that a script should be rendered with an async attribute, or included in a preload list.
In another project using this asset loader, a team recently wrote a custom wrapper which used this logic to set the "defaults" for scripts:
- If async is not explicitly set, and the script has no dependencies, then default to async loading.
- If defer is not explicitly set, but the script has dependencies, then default to defer loading.
Then when registering the script the wrapper would add the relevant parameters:
foreach ( [ 'async', 'defer' ] as $attr ) {
if ( ! empty( $args[ $attr ] ) ) {
wp_script_add_data( $args['handle'], $attr, true );
break;
}
}
Then, filter the script based on that data:
function filter_script_loader_tag( string $tag, string $handle ) : string {
foreach ( [ 'async', 'defer' ] as $attr ) {
if ( ! wp_scripts()->get_data( $handle, $attr ) ) {
continue;
}
// Prevent adding attribute when already added in #12009.
if ( ! preg_match( ":\s$attr(=|>|\s):", $tag ) ) {
$tag = preg_replace( ':(?=></script>):', " $attr", $tag, 1 );
}
// Only allow async or defer, not both.
break;
}
return $tag;
}
The note about #12009 refers to this ticket to add async and defer handling to core wp_enqueue_script itself.
We should have a way of registering that a script should be rendered with an
asyncattribute, or included in apreloadlist.In another project using this asset loader, a team recently wrote a custom wrapper which used this logic to set the "defaults" for scripts:
Then when registering the script the wrapper would add the relevant parameters:
Then, filter the script based on that data:
The note about
#12009refers to this ticket to add async and defer handling to core wp_enqueue_script itself.