Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enqueue javascript with type="module"

I want to use countUp.js on my custom theme in Wordpress.

When I add the file with wp_enqueue_script(), I get an error:

Uncaught SyntaxError: Unexpected token 'export'

I've read that it can be fixed setting on the <script> label type="module", but I don't know how to do that, as that option doesn't exist in wp_enqueue_script()...

Anyone can hel me?

like image 938
lopandpe Avatar asked Nov 19 '19 09:11

lopandpe


1 Answers

One can add attributes to a script by applying filter 'script_loader_tag'.

Use add_filter('script_loader_tag', 'add_type_attribute' , 10, 3); to add the filter.

Define the callback function like the example given on the link above:

function add_type_attribute($tag, $handle, $src) {
    // if not your script, do nothing and return original $tag
    if ( 'your-script-handle' !== $handle ) {
        return $tag;
    }
    // change the script tag by adding type="module" and return it.
    $tag = '<script type="module" src="' . esc_url( $src ) . '"></script>';
    return $tag;
}
like image 105
Paul Naveda Avatar answered Nov 12 '22 21:11

Paul Naveda