Enqueue javascript with type=“module”

筅森魡賤 提交于 2020-07-18 05:09:50

问题


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 label type="module", but I don't know how to do that, as that option does'nt exixst in wp_enqueue_script...

Anyone can hel me?


回答1:


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;
}


来源:https://stackoverflow.com/questions/58931144/enqueue-javascript-with-type-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!