How to execute javascript AFTER build?

In the solution of another question there is the following script mentioned which does manipulate the DOM in a very simple manner (search and replace + remove):

(function() {
  var i, text, code, codes = document.getElementsByTagName('code');
  for (i = 0; i < codes.length;) {
    code = codes[i];
    if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
      text = code.textContent;
      if (/^\$[^$]/.test(text) && /[^$]\$$/.test(text)) {
        text = text.replace(/^\$/, '\\(').replace(/\$$/, '\\)');
        code.textContent = text;
      }
      if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
          /^\$(.|\s)+\$$/.test(text) ||
          /^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
        code.outerHTML = code.innerHTML;  // remove <code></code>
        continue;
      }
    }
    i++;
  }
})();

To improve the performance of my website I would like to execute the javascript on build.

If possible I would like to do this “in Hugo” not with a separate bash script or something like that. Is this even possible? How?

I may be dumb but don’t you need the DOM tree to be ready so you can apply the changes you need and the DOM will only be available after Hugo build the .html files? So, as you are not rewritten the already generated HTML files, I don’t understand the need to do it on build time, sorry!

(You’re right! I changed the title from “on build” to “after build”.)

So manipulating the .html files (generated by Hugo) can’t be done “in Hugo”?

I asked because I thought there is something like a “post build processor” or some “after build hook” or anything like that. I’m looking for something like “if the .html files are generated, then execute this script.”

How would you do this?

You can use resources.PostProcess to delay processing to after the build, the main reason I added it was to do CSS purging with PostCSS. That said, the output from Hugo is not a DOM, we produce (mainly) HTML files. The browser produces the DOM.

1 Like

Yeah, like Bep mentioned, there’s no official way to do without a script dependency of some sort that will parse all .html generated by Hugo.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.