How do you enqueue script tags for ReactDOM in WordPress’ functions.php?

So I’m thinking you can use the script_loader_tag filter to replace HTML as the script is being loaded in. This will allow you to control where you’re enqueueing the script as usual via wp_enqueue_scripts hook while still allowing you to add in any script attributes.

The Enqueue

/**
 * Enqueue whatever script we may need
 *
 * @return void
 */
function wpse302526_enqueue_react() {

    wp_enqueue_script(
        'react',    // File handle/slug
        $file_url,      // URL to file
        array(),        // Dependencies
        false,          // Version
        true            // Add to Header ( false ) or Footer ( true )
    );

}
add_action( 'wp_enqueue_scripts', 'wpse302526_enqueue_react' );

We’ll target the script specifically by the handle/script slug.

The Find / Replace

/**
 * Modify the enqueue script tag
 *
 * @param String $html      - Generated script HTML
 * @param String $handle    - Script slug/handle
 *
 * @return $html
 */
function wpse302526_modify_script_tags( $html, $handle ) {

    /** Add script attribute **/
    if( 'react' === $handle ) {

        /* Add `crossorigin` attribute */
        $html = str_replace(
            '<script',
            '<script crossorigin',
            $html
        );

        /* Initialize ReactDOM */
        $html = str_replace(
            '</script>',
            'window.ReactDOM</script>',
            $html
        );

    }

    return $html;

}
add_filter( 'script_loader_tag', 'wpse302526_modify_script_tags', 10, 2 );

I feel like if you can you should avoid doing this part outside your enqueue as it could be confusing to any developers who run across it. Keeping all your enqueues and script URLs in one place ( instead of torn between the two filters ) seems for the best. If you can’t avoid it then feel free to add it in.

document.write('<script crossorigin src="https://wordpress.stackexchange.com/questions/302526/<?php get_template_directory_uri() ?>/react-dom.development.js"><\/script>')

If you absolutely need the above line, then I would go with the wp_footer approach to keep everything in one place.

Leave a Comment