So how does Autoptimize work anyway?

A question that has come up a couple of times already is how Autoptimize and it’s cache work. So let’s do some copy/pasting of what I replied earlier on the wordpress.org support forum;

  1. AO intercepts the HTML created by WordPress for a request (using the output buffer)
  2. all references to JS (and CSS) are extracted from the HTML
  3. all original references to JS (and CSS) are removed from the HTML (the code in the original files is left as is, AO never changes those files)
  4. all JS (and CSS) is aggregated (JS in one string, CSS in as many strings as there were media types)
  5. the md5-hash (mathematical/ cryptographic function that generates a quasi-unique string based on another string) of the aggregated JS (and CSS) is calculated
  6. using the md5 AO checks if a cached file with that md5 exists and if so continues to step 8
  7. if no cached file is found, the JS (and CSS) is minified and cached in a new file, with the md5 as part of the filename
  8. the links to the autoptimized JS (and CSS) file in cache are injected in the HTML
  9. the HTML is minified (but not cached in Autoptimize)
  10. the HTML is returned to WordPress (where it can be cached by a page cache and sent to the visitor)

This is especially interesting if you want to understand why the cache size can “explode”; if in step 4 the code is even a bit different from previous requests, the md5-hash in step 5 will be different so the file will not be found in cache (step 6) and the code will be re-minified (which is relatively expensive) and cached (step 7).
And that, my friends, is how Autoptimize works.