How to echo JS right after enqueued script to put it into noConflict mode?

You have to filter script_loader_src, check if you are on the correct script and add a one-time filter for clean_url. Then add your extra script, and make sure the output is syntactically valid.

Pretty simple, albeit rather hacky.

class Extra_Script
{
    private $extra = [];
    private $handle;
    private $url;
    private $versioned_url;

    public function __construct( $handle, $url )
    {
        $this->handle = $handle;
        $this->url    = $url;
        add_filter( 'script_loader_src', array( $this, 'filter_script_src' ), 10, 2 );
    }

    public function add_script( $script )
    {
        $this->extra[] = $script;
    }

    public function filter_script_src( $src, $handle )
    {
        if ( empty ( $this->extra ) )
            return $src;

        if ( $this->handle !== $handle )
            return $src;

        if ( 0 !== strpos( $src, $this->url ) )
            return $src;

        $this->versioned_url = $src;

        add_filter( 'clean_url', array( $this, 'filter_esc_url' ) );
        remove_filter( current_filter(), array( $this, __FUNCTION__ ) );

        return $src;
    }

    public function filter_esc_url( $url )
    {
        if ( $url !== $this->versioned_url )
            return $url;

        remove_filter( current_filter(), array( $this, __FUNCTION__ ) );

        $scripts = join( "\n", $this->extra );

        return "$url'></script><script>$scripts</script><script class="";
    }
}

Usage

add_action( "wp_enqueue_scripts', function()
{
    $handle="foo";
    $url    = plugins_url( '/foo.js', __FILE__ );

    wp_enqueue_script( $handle, $url );

    $extra = new Extra_Script( $handle, $url );
    $extra->add_script( "alert('bar!');" );
});

This will add an inline script right after your enqueued script.

An alternative might be Patchwork. You can redefine WordPress’ code at runtime with that. But that wouldn’t be less hacky.

Leave a Comment