Dear Developers, Stop Loading Admin Scripts & Styles On Every Page

Development 2 min read
As my last post on a subject very similar to this likely rose some eyebrows, this one is sure to garner some attention. WordPress plugins & themes are almost all unilaterally guilty of loading admin scripts and styles on every page. There is virtually no reason for this. Let's talk about loading CSS and JavaScript in the WordPress admin panel. This is almost always an issue when users complain about poor performance. Loading CSS and JavaScript becomes a hassle when you are using a lot of plugins on your website. This is because you cannot install Autoptimize to have it combine them into one file. Or defer the JavaScript to reduce the render time.

Simple Way to Load a CSS File

This is a simple way of loading CSS files that almost everyone uses because it is super easy.
function load_custom_wp_admin_style() {
        wp_register_style( 'custom_wp_admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );
        wp_enqueue_style( 'custom_wp_admin_css' );
}
add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );
This method sucks because if you have an incredibly simple plugin that doesn't need to be used on any page, except the options panels; then you just loaded a CSS sheet on every... single... page. This example is nearly identical for JavaScript files.

The Better Way to Load CSS Files

Now we are going to load this CSS sheet on a specific plugin's page within the admin panel.
function load_custom_wp_admin_style($hook) {
        // Load only on ?page=mypluginname
        if($hook != 'toplevel_page_mypluginname') {
                return;
        }
        wp_enqueue_style( 'custom_wp_admin_css', plugins_url('admin-style.css', __FILE__) );
}
add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );
The above code can also be adopted for themes by changing the hook URL. Additionally, this can also be applied to JavaScript files. While the above code is a solid way to fix the issue, it is something that shouldn't need to be fixed in the first place. What are your thoughts on the above issue is it something that should be fixed?
Scott Hartley

Scott Hartley

Founder & CEO, Sert Media

Founder and CEO of Sert Media, a Nashville-based digital marketing agency. Scott has spent over 15 years helping businesses grow through SEO, web performance optimization, and strategic digital marketing. His deep expertise in WordPress development, site speed, and technical SEO has guided hundreds of brands toward measurable results. When he's not auditing Core Web Vitals or refining campaign strategies, he's writing about the tools, techniques, and trends shaping the modern web.

Leave a Comment

Your email address will not be published. Required fields are marked with an asterisk.

Related Articles