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="https://unpkg.com/rough-notation/lib/rough-notation.iife.js"></script> <!-- IIFE version -->
<script>
setTimeout(() => {
import { annotate } from 'rough-notation';
const e = document.querySelector('.main-article-idea');
console.log(e, 'run')
const annotation = annotate(e, { type: 'underline' });
annotation.show();
}, 2000);
</script>
Error:
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() {
?>
<script>
// your javscript code goes
</script>
<?php
}
add_action('wp_footer', 'wpb_hook_javascript_footer');
Leave an answer