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
The beauty of this solution is that you can use that action hook for many other things too.
Did this help you? Was this stupid? Let me know with a comment. I love interacting with other developers!