Tarik Hamilton

A web developer actively writing about Vue.js, Laravel, WordPress, and more.

Adding Scripts After the Opening Body Tag the WordPress Way

Note: I work really hard on my featured images for my posts. I made this post’s image before Pepe became an Alt-Right mascot. Just know that there isn’t any political context surrounding his existence in the image. Thanks.

Note (2018/01/28): Google nor Twitter specify placing scripts after the opening body tag anymore. This page exists for historical purposes.

With the rise of vendor scripts being async by default, many vendors are asking for these scripts to be placed after the opening body tag. At the time of writing this, I have seen this recommendation from the Facebook SDK, Google Tag Manager, and Twitter’s widgets-js.

In WordPress, using wp_enqueue_styles, I’m sure you’ve noticed you can either have your script in the footer or the head, but no where else.

In all honesty, I don’t know if the before opening tag requirement is necessarily a true requirement or just for better results than the footer, but hey, I don’t want any trouble. We can easily keep these scripts away from our header.php.

Check it out below.

What’s Going On

If you haven’t used action hooks before, this is a great way to understand their power and usage in WordPress. In our header.php, immediately after the body we create an action hook. Then in our functions.php (or wherever you’d like to keep this code, but let’s keep to standard!), we read our JavaScript file and echo its contents into a script tag.

The beauty of this solution is that you can use that action hook for many other things too.


The only disadvantage here is that there is nothing to help manage JavaScript dependencies. Also, we aren’t using wp_enqueue_script anymore. In PHP, you can’t extend or overwrite functions, so unfortunately we have to bend the rules a little, but hey, this is open source. Just don’t go too crazy.

The file I used is a concatenated file with Gulp. Recently, I’ve been using Webpack to manage my JavaScript and their dependencies too, so there are ways to get around this downfall. The single file is great for less HTTP requests, especially considering how minute these scripts I use typically are.

That’s It

Did this help you? Was this stupid? Let me know with a comment. I love interacting with other developers!