Print minified JS directly into <head>?

I have some JS that I need to insert into the <head> of base.php. Mainly to avoid FOUC stuff. It’s Vanilla JS so I’m not worried about deps.

I can think of a few ways to get it in there (brute force, php include…) but what I’d really like to do is have the ability to work on a normal version of it and have a minified version inserted into the head. I don’t want to enqueue it—I want it printed directly into the HTML.

Is there way to do this with the current gulp setup? Current project is based on Sage 8.2.1.

Create a new Javascript file. Follow the example in our manifest to inform the asset pipeline how to output it.

Here’s an example of how we create customizer.js in the dist folder.

https://github.com/roots/sage/blob/master/assets/manifest.json#L15-L19

So let’s say you go with…

    "inline.js": {
      "files": [
        "scripts/inline.js"
      ]
    },

Once you do that, you can use PHP to pull its contents from the dist folder. Something like this should work…

<script><?php readfile(get_template_directory() . '/dist/scripts/' . basename(Roots\Sage\Assets\asset_path('scripts/inline.js'))); ?></script>

There are obviously more elegant ways of doing it, but this will get the job done using the tools and code we already have in place.

(Note: This is all untested. I wrote this right here in the post editor, so be on the lookout for screwed up syntax or something.)

2 Likes

Aces! Thank you. Will report back.

Worked a charm. Thanks again @QWp6t.