One of the things that are all too common, though, especially as it relates to the administrative area, is loading assets in WordPress on screens where they aren’t needed.
It’s completely possible to make an argument that given the file sizes or the functionality that each present, the files are only impacting a minimal amount of load time at best, right?
But match this mentality with who-knows-how-many plugins, and you’ve got more than a heavy impact happening on a given payload.
So what can we do?
Loading Assets in WordPress
One of the easiest things that you can do is check which page you’re on and then, if it’s a page that needs a given asset or set of assets, you can load them.
I’ll talk about the details later since I’m trying to keep this as quick as possible. Generally speaking though, look at the page and if it doesn’t need the asset(s), then don’t load them:
For those interested in a bit more detail, here you go:
- The function opens with a guard clause. It uses the get_current_screen() function that returns a WP_Screen object. I use the ID property to determine if we’re on the dashboard or not. If not, then I leave the function.
- If we are on the dashboard, then I’ll add the asset. In this case, I’m using wp_enqueue_style for the stylesheet I have available.
This particular process is repeatable no matter what kind of asset you’re adding. It’s a two-step process, really:
- Check to see if you’re on the page you need to be on and exit if you aren’t.
- If so, add the asset(s).
This can go a long way in the optimization of loading assets in WordPress especially when used in conjunction with other plugins that may not be as responsible.