Skip to content

Support script attributes like "async", "defer", "preload" #49

Description

@kadamwhite

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions