# Using requirejs in WordPress posts

While porting this blog to WordPress as an experiment, I came across a pretty frequent problem: using requirejs in a WordPress post. In my case, requirejs is needed to use my TypeScript libraries from https://github.com/carlonluca/isogeometric-analysis in the post, to create the plots you see in this post.

It was not simple at all to use it in Google Blogger, WordPress does not seem to behave very differently in this regard. When the post is rendered, I get errors like:

Uncaught Error: Mismatched anonymous define() module: […]

This may be related to the fact that something in WordPress or its plugins looks for that symbol and gets confused when another one is defined in the post. I found many pages treating this problem, but no solution satisfied me, either because it did not work or because I did not like it. I’d prefer the solution to be entirely contained in the post itself, I won’t probably use requirejs often.

This is the way I solved the problem: let’s give the time to WordPress and all its plugins to load and settle. Then, start loading requirejs and all the other deps we need in a script. This is an example for my specific use case:

<script>
window.PlotlyConfig = {MathJaxConfig: 'local'}
</script>
[...]
<script>
$.getScript('https://requirejs.org/docs/release/2.3.6/comments/require.js', function() {$.getScript('https://carlonluca.github.io/isogeometric-analysis/dist/bundle.js', function() {
require(["nurbs/drawNurbsCurveExample"], function(d) {
d.drawNurbsCurveExample1("nurbsCurve1", true)
d.drawNurbsCurveExample2("nurbsCurve2", true, "nurbsBasis2")
d.drawNurbsCurveExampleCircle("nurbsCurve3", true, "nurbsBasis3")
})
require(["nurbs/drawNurbsSurfExamples"], function(d) {
d.drawNurbsSurfPlateHole("nurbsSurf1", true)
d.drawNurbsSurfToroid("nurbsSurf2", true)
})
})
})
}, false)
</script>

To do this, I used jQuery. So, first of all jQuery is loaded. Then, on the onload event, I load requirejs. When requirejs is loaded, I then load my library, which needs requirejs, and then I can freely use it in the post. Note that simply adding script elements was not sufficient, the order must be preserved and the callbacks must be used to ensure the proper chain is respected.

This approach is a little verbose, but allows me to leave the rest of the theme unchanged and confines the mess to the specific posts needing these structures.