Filtering HTML Script Tags With script_loader_tag

Recently, while speaking at WordCamp Philly 2015, I referenced the usage of script_loader_tag to async JavaScript files. The reaction that I received proved that there are still a lot of developers who are not aware of this handy function.

To be honest, I wasn’t aware of it myself until a couple of months ago. While working on a client project, Mary Cadwell (@marycadwell), who is the Engineering Manager for this project, suggested usingscript_loader_tag to filter a JavaScript file after enqueuing the script. After some quick research, I realized that this handy filter could solve many issues that I have seen in the past, one of which is using native WordPress functions to async a JavaScript file.

Let’s take a look at simple implementation usingscript_loader_tag. This should start with enqueuing a JavaScript file as such:

After the JavaScript file has been enqueued, we will target the file usingscript_loader_tag:

You’ll first notice that we are running a check on the handle of the script. This is the handle parameter assigned to the script when it was initially enqueued. This check looks at the handle and if the handle does not match ‘theme-scripts’, as shown in this example, the tag will return. This ensures that only the JavaScript file with the matching handle is being used.

Second, you’ll notice that we are using str_replace to search for<script, replacing it with<script async, and calling$tag afterwards so that the appropriate tag is being modified.

The final result, if viewing the code, would render the JavaScript as:

The possibilities can be endless as to how we can usescript_loader_tag.

Let’s say that you have a script that tracks visitors on your site. With this script, you need to append the JavaScript file with a site ID so that the data would tracked. This is how we could accomplish this:

The final result, if viewing the code, would render the JavaScript as:

Have you had a chance to usescript_loader_tag in any of your projects? If so, I’d love to hear about it. As always, leave a comment!