A developer’s life beyond the screen.


Dev Tip #6: Safely Loading JavaScript and CSS in Your Plugin

Loading scripts the wrong way can break compatibility, affect performance, or mess up other plugins.
Here’s how I handle script loading in WordPress the right way — clean, safe, and conflict-free.


1. Use wp_enqueue_script() and wp_enqueue_style()

Always enqueue scripts. Never hardcode them into the page.

add_action( 'admin_enqueue_scripts', 'my_plugin_admin_assets' );

function my_plugin_admin_assets( $hook ) {
    if ( $hook !== 'toplevel_page_my-plugin' ) return;

    wp_enqueue_style(
        'my-plugin-style',
        plugin_dir_url( __FILE__ ) . 'assets/css/admin.css',
        [],
        '1.0.0'
    );

    wp_enqueue_script(
        'my-plugin-script',
        plugin_dir_url( __FILE__ ) . 'assets/js/admin.js',
        [ 'jquery' ],
        '1.0.0',
        true // load in footer
    );
}

2. Load Assets Only When Needed

Use the $hook parameter to load scripts only on specific admin pages.

This reduces bloat and prevents conflicts.


3. Use plugins_url() or plugin_dir_url()

Avoid hardcoding plugin paths. Use WordPress functions to make your URLs dynamic.

plugin_dir_url( __FILE__ ) . 'assets/js/script.js';

4. Add Versioning to Bust Cache

Always version your scripts and styles, especially during development.

wp_enqueue_style( 'my-plugin-css', $url, [], '1.1.2' );

Use filemtime() during dev to avoid caching issues:

wp_enqueue_style( 'my-plugin-css', $url, [], filemtime( $path ) );

5. Respect Dependencies

If your script depends on jQuery or WP libraries, declare them properly.

wp_enqueue_script( 'my-js', $url, [ 'jquery', 'wp-util' ], '1.0.0', true );

Final Thought

Good plugins don’t just work — they play well with others.

Loading your assets the right way keeps your plugin fast, safe, and conflict-free — especially on sites running 20+ other plugins.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *