How can I use a Javascript module in a wordpress post (in single posts – or a template level)


I found this post which provides some good advice to solve the issue: How can I load a javascript file that is type=”module” the WordPress way?

It is not however clear to me how make it in a fully granular way (e.g. per-post / page).

For example, this is injected directly in the HTML of a post, but does not work in any browser which supports ES6 natively:

<script type="module" src=""></script> <!-- IIFE version -->
setTimeout(() => {
import { annotate } from 'rough-notation';

const e = document.querySelector('.main-article-idea');
console.log(e, 'run')
const annotation = annotate(e, { type: 'underline' });;

}, 2000);


Uncaught SyntaxError: Cannot use import statement outside a module

Another interesting approach is by implementing the javascript function in a WordPress hook in functions.php, and If that’s a good solution, I would like to have direction how to do it in my concrete example:

function wpb_hook_javascript_footer() {
          // your javscript code goes
add_action('wp_footer', 'wpb_hook_javascript_footer');
dragonmnl 3 years 2020-05-29T07:11:36-05:00 0 Answers 90 views 0

Leave an answer