Using Dynamic Hashes in File Names with WordPress’ Enqueue Function

Share this:

The following is a guest post by Pascal Klau, a self-described trainee web developer from Germany working with WordPress, Gulp, and more recently VueJS and Webpack.

During my journey of learning web technology, I stumbled upon the importance of file caching. It's a pretty important thing for web page performance. I also sometimes notice that when a file was changed, and you refreshed the page, the browser can still be using the old version (because of the cache). There is a solution!

Hashes Break Caches

Adding a hash in the file name lets the browser think it is a totally different file. Thus, "breaking the cache". For example, if the file `main.3hZ9.js` changes to `main.8a3s.js`, the browser will definitely re-download it. This renaming can be done automatically by task runners.

There is a problem for those of us using WordPress though. You need to manually enqueue the files by name but you can't know the randomly generated hash value.

In WordPress, any asset you enqueue may need dependencies. You declare these yourself by passing an array of them to the enqueue function. Here, we're checking the file and adding dependencies if needed:

I am bundling JavaScript files into `main.js` and `vendor.js` (in my case, with Webpack). When editing `main.js`, the timestamp for `vendor.js` changes as well. So it would be downloaded every time without being any different at all.

Hashes, on the other hand, stay the same.

Conclusion

Now you can add hashes dynamically to files when they change, through Gulp. And you can enqueue those files in WordPress without needing to know the new file names directory.

you don’t want to edit the hash manually every time you save the file. Let PHP do that.
You could use PHP filemtime for that.
But the reason it might not be the thing you want, is stated at the end of the article. :)

👋

CSS-Tricks* is created, written by, and maintained by Chris Coyier and a team of swell people. It is built on WordPress and powered up by Jetpack. It is made possible through sponsorships from products and services we like.