• Add async attribute to enqueued WordPress script

    <?php
    
    namespace NickDavis\AsyncExample;
    
    const ASYNC_EXAMPLE = 'nd-async-example';
    
    add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\enqueue_script' );
    /**
     * Enqueues the async example script.
     *
     * @since v1.0.0
     */
    function enqueue_script() {
    	wp_enqueue_script( ASYNC_EXAMPLE, '//async.example.com', [], null, true );
    }
    
    add_filter( 'script_loader_tag', __NAMESPACE__ . '\add_async_attribute', 10, 2 );
    /**
     * Add an aysnc attribute to an enqueued script.
     *
     * @url https://wordpress.stackexchange.com/a/198372
     *
     * @since v1.0.0
     *
     * @param string $tag Tag for the enqueued script.
     * @param string $handle The script's registered handle.
     * @return string Script tag for the enqueued script
     */
    function add_async_attribute( $tag, $handle ) {
        // Just return the tag normally if this isn't one we want to async.
        if ( ASYNC_EXAMPLE !== $handle ) {
            return $tag;
        }
    
        return str_replace( ' src', ' async src', $tag );
    }