Run JavaScript directly in head

Hey there everybody.

I am contributing to a website called Millmint. The website has a dark/light theme toggle on in the header which allows you to switch the theme. The problem is that on the initial page load, it always flashes a white screen. Of course this is a fairly well-known problem with this kind of system with a simple enough fix: just put a script at the top of the head that sets the appropriate attributes.

The problem with this approach is that Hugo seems to be adding an invalid type attribute to the script until page load, where it replaces the invalid type="ff4237ef3f44fdfad52b1258-text/javascript" with the much more valid type="text/javascript", after which it finally runs. If you “view source” on the website, you’ll see that it has this invalid type attribute at the very top.

The code is available here, with the relevant bit highlighted:

Is there any way to make Hugo leave this specific script tag alone? It doesn’t add the attribute on the local dev server as it does in the production build, and that’s the desired behaviour.

I should also mention I’ve read through JavaScript Building | Hugo but did not seem to find a solution there. I’ve also tried Googling the problem with queries similar to my title with no results.

The identifier (or whatever it is) is not added by Hugo. Look to your JS.

When I build your site locally and cat public/index.html

    if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        document.documentElement.setAttribute("data-theme", "dark");
    } else {
        document.documentElement.setAttribute("data-theme", "light");

You are absolutely right, I’m very sorry for not verifying it was a Hugo issue before posting. I just checked the build and the attributes are nowhere to be found.

I’ll continue investigating. Perhaps it’s a CloudFlare feature of sorts, or GitHub Pages, or something.

Thank you for your time!

1 Like