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
runaction method on the proper hook.
As you probably guessed by now, the assets handlers need to inherit the
AssetsHandlerInterfaceinterface. 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
runaction 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
.minextension at the same location. If said file is present and the constant
SCRIPT_DEBUGis not set to true, the minified file will be enqueued instead. Moreover, the file's version will be the output of the
filemtimefunction. If that fails, it falls back to a given fallback version.
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:
SetupStylesTraitfor calling the
register_stylesmethod on setup
SetupScriptsTraitfor calling the
register_scriptsmethod on setup
SetupScriptsStylesTraitfor calling the
register_scripts_and_stylesmethod on setup