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

Home » WordPress Tutorials » Dear Developers, Stop Loading Admin Scripts & Styles On Every Page

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

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?

By |2018-07-16T11:19:27+00:00July 16th, 2018|Categories: WordPress Tutorials|0 Comments

About the Author:

Scott Hartley is a WordPress Developer who focuses on website performance optimization, SEO, and security. He can't tell you what a color wheel is but he knows the intricacies of making a website load quickly.

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.