humanmade / humanmade/asset-loader
Support script attributes like "async", "defer", "preload"
- Dominant language
- PHP
- Stars
- 26
- Forks
- 2
- PR merge metrics
- No merged PRs in 30d
Description
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:
```php
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( ':(?=>):', " $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](https://core.trac.wordpress.org/ticket/12009).
Contributor guide
Assessment
This issue has not been assessed yet.