Assets Service
The assets service is an example of a multi-handler service. WordPress differentiates between two types of assets: scripts (JS files) and styles (CSS files). The service itself tries to be as agnostic as possible of this in order to let you build handlers for other types of assets as well.
However, the WP scripts API is similar but slightly different from the WP styles API. Trying to find a common denominator was not easy -- the only thing the two have in common is the hook that they should be enqueued on! For this reason, the Assets Service is unique because it doesn't have any public method and most interactions happen at the handler level. The basic function of the service, therefore, is to act as a container for the assets handlers and to call their run action method on the proper hook.
As you probably guessed by now, the assets handlers need to inherit the AssetsHandlerInterface interface. Because of no unified WordPress API for working with assets, the interface doesn't implement any methods and simply acts as a way to validate handlers registered with the service.
There are 2 handlers that come pre-packaged with the module:
Both of them behave similarly to the default hooks handler and to the default shortcodes handler, namely they store the scripts and styles to be registered and enqueued in their own arrays, respectively, until the run action method is called on the handler instance. This ensures that errors during the plugin's initialization prevent the service from enqueueing any extraneous asset files.
The handlers perform two crucial tasks automatically though:
  • cache busting based on the file's last modified time
  • automagically enqueueing the minified version, if it exists
Basically, both handlers look at the registered assets and look for a file containing the notorious .min extension at the same location. If said file is present and the constant SCRIPT_DEBUG is not set to true, the minified file will be enqueued instead. Moreover, the file's version will be the output of the filemtime function. If that fails, it falls back to a given fallback version.
For assets enqueued from a CDN (or, in general, an external URL), the given version string is used by default instead.

Working with the service

As mentioned above, the assets service is unique as being the only service that delegates most of the work to its handlers. Therefore, it's recommended to use one of the 3 setup traits in order to get the singleton handler instance automagically:
  • the SetupStylesTrait for calling the register_styles method on setup
  • the SetupScriptsTrait for calling the register_scripts method on setup
  • the SetupScriptsStylesTrait for calling the register_scripts_and_styles method on setup
The coding example is similar to the one presented on the Hooks Service page.
Copy link