WordPress: Only register your asset until it’s needed
Published: – Leave a comment
More often than I want, I see directly enqueuing assets via wp_enqueue_script or wp_enqueue_style without checking whether the asset is actually used on the current page. This may hurt performance. But it also has a negative implication for developers.
Difference between register and enqueue
To understand the problem, let’s checkout what the actual difference is between registering and enqueueing an asset (script or style). When you register an asset, you tell WordPress where to find the asset URL and which dependencies to other assets it has. When you enqueue an asset, it depends. If the asset is unknown to WordPress at this moment, it also registers it. And afterwards, the asset is directly added to the queue to be printed on the current page directly.
The problem with direct enqueueing
The first problem is the obvious one: whenever the asset is enqueued, it must be loaded by the client when accessing the page. When properly defined, the asset loads only when necessary (which it should). But that creates another problem.
A direct enqueueing lacks flexibility. Either the asset is directly printed on the page or it is not available at all. Especially for third parties, this may be a problem when extending your asset, but it can also affect yourself when extending it.
Decouple registering
The solution is fairly straight forward: Always register, but only enqueue when necessary. This way, WordPress is always aware of the asset, and you – or any third party – can enqueue it afterwards whenever needed.
„Just dequeue it“
You maybe think that this problem is rather synthetic, since you can just dequeue any enqueued asset before it’s actually printed. But there we already have the problem. Some assets are rendered in the head, others in the footer of the page. It’s also strictly necessary to check the point in time and priority when the asset is being enqueued. Thus, it’s a sisyphean task to dequeue an asset you don’t want to have enqueued on a page. And there are also other caveats, depending on where and how the asset is actually enqueued, and having to manually remove it from the script/style registry ($wp_scripts/$wp_styles) definitely is only a workaround.
Reposts