WPGEARED2.0.
Performance

wp_enqueue_scripts: load CSS and JavaScript correctly

Published
Share Report:

Use the wp_enqueue_scripts hook to load front-end CSS and JavaScript through WordPress. Inside its callback, call wp_enqueue_style() for a stylesheet and wp_enqueue_script() for a classic script. Give each asset a handle, declare its dependencies and load it only on the pages that need it.

Despite its name, the hook covers styles too. Use the enqueue functions inside it to schedule individual files. The hook reference makes that distinction.

This example builds a small component on single blog posts. It uses plain JavaScript, an explicit file version and public inline configuration. It does not remove other plugins' assets or promise a particular PageSpeed score.

1. Create the plugin and its asset files

Work on local WordPress or staging, with a backup and file access for recovery. The main example requires WordPress 6.3 or newer because it uses the script strategy argument, introduced in that release according to the function reference checked in November 2026.

Create this structure:

wp-content/plugins/wpgeared-assets/
├── wpgeared-assets.php
└── assets/
    ├── site.css
    └── site.js

Put the complete PHP below in wpgeared-assets.php:

<?php
/**
 * Plugin Name: WPGeared Asset Examples
 * Version: 1.0.0
 * Requires at least: 6.3
 */
defined( 'ABSPATH' ) || exit;

function wpgeared_enqueue_assets() {
    if ( ! is_singular( 'post' ) ) {
        return;
    }
    wp_enqueue_style(
        'wpgeared-site',
        plugins_url( 'assets/site.css', __FILE__ ),
        array(),
        '1.0.0'
    );
    wp_enqueue_script(
        'wpgeared-site',
        plugins_url( 'assets/site.js', __FILE__ ),
        array(),
        '1.0.0',
        array( 'strategy' => 'defer', 'in_footer' => true )
    );
    wp_add_inline_script(
        'wpgeared-site',
        'window.wpgearedAssets = ' . wp_json_encode(
            array( 'message' => 'The post assets loaded.' ),
            JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
        ) . ';',
        'before'
    );
}
add_action( 'wp_enqueue_scripts', 'wpgeared_enqueue_assets' );

Put this in assets/site.js:

(() => {
    const config = window.wpgearedAssets || {};
    document.querySelectorAll('.wpgeared-asset-demo').forEach((element) => {
        element.textContent = config.message || 'Assets ready.';
        element.classList.add('is-ready');
    });
})();

Put this in assets/site.css:

.wpgeared-asset-demo {
    padding: 1rem;
    border: 2px solid #64748b;
    overflow-wrap: anywhere;
}
.wpgeared-asset-demo.is-ready {
    border-color: #166534;
}

Activate WPGeared Asset Examples. On a test blog post, add a Custom HTML block containing:

<p class="wpgeared-asset-demo">Waiting for the post assets.</p>

Save and view the post on the front end. The CSS gives the paragraph a border. The JavaScript changes its text and adds the class that changes the border color. It uses textContent, not innerHTML, because the configuration contains text rather than trusted HTML.

The assets load on every single post, even one without that paragraph. The condition checks the page type, not whether the component is present. For a real block component, block metadata is often a better place to declare its assets.

2. Understand handles, URLs and dependencies

wpgeared-site is the asset handle. WordPress uses it to track the registration, dependencies and enqueue state. Script and style handles have separate registries, so using the same string for this pair is intentional.

plugins_url() produces a browser URL relative to the plugin file. A filesystem path such as /var/www/... is not a substitute. Conversely, a function that reads a local file needs a filesystem path, not its public URL. Mixing these two is a common reason an asset request returns 404.

The empty dependency arrays are correct because the JavaScript is vanilla and the stylesheet is independent. If a script genuinely uses jQuery, declare the registered jquery handle as a dependency rather than a URL or filename. Write that code for WordPress's jQuery environment, including its no-conflict behavior. Do not add jQuery merely because a copied snippet has it in the array.

Enqueuing schedules an asset for output. Registration stores its details without necessarily scheduling it yet. The enqueue functions can do both in one call, as this example does. Use a unique handle and one authoritative registration instead of trying to overwrite another component's handle with a different URL. See the script and style references.

3. Keep versions stable and strategies deliberate

The example uses 1.0.0 as its file version. Change it when you release changed assets. This changes the versioned URL, which helps caches distinguish old and new files. It is not a guarantee that every page cache or CDN is immediately purged.

Do not use time() as the version on every request. That continually changes the URL and defeats useful browser caching. A file-modification version can be an alternative during development, but guard local file reads and keep the path separate from the asset URL. A stable release version is simpler for this example.

in_footer asks WordPress to place the classic script in the footer group. The theme must include the normal WordPress head and footer hooks for queued assets to be printed.

strategy => 'defer' requests deferred execution. Deferred classic scripts run after document parsing and preserve their execution order. async is not a drop-in replacement for code that depends on ordered execution.

There is no default loading strategy in this API. WordPress also considers dependencies when deciding which requested strategy is eligible, so inspect the emitted tag rather than assuming your argument guarantees the final attribute. This behavior is documented in the wp_enqueue_script reference.

4. Attach public inline data safely

The PHP calls wp_add_inline_script() for the same handle, in the before position. The resulting configuration is available before site.js reads it.

wp_json_encode() serializes the data. The hexadecimal escaping flags keep HTML-sensitive characters out of the raw inline string. Avoid hand-built JavaScript such as concatenating a user's name into quoted source code. Also avoid putting secrets in this object: anything sent to a page is visible to its visitor. The JSON function reference covers the serializer.

Pass JavaScript source without <script> tags to wp_add_inline_script(). Attach it while the handle is registered and before WordPress prints it. An inline block placed after a deferred script is not a safe general recipe for assuming the external file has already executed. See the inline-script reference.

5. Choose the hook for the screen

Asset location Appropriate hook or API
Normal front-end page wp_enqueue_scripts
An administration screen admin_enqueue_scripts
Block content in the editor and front end Block metadata, or enqueue_block_assets where appropriate
The block editor's interface enqueue_block_editor_assets

The admin hook receives the screen's hook suffix. Use it to limit a dashboard-specific asset instead of loading it across every admin page. The admin hook reference includes that parameter.

The editor interface and the content canvas are not the same document in an iframed editor. CSS queued for the outer interface does not automatically style the canvas. Use the intended block-content mechanism rather than relying on an incidental selector match. The editor asset guide explains the distinction.

For a custom block, the block.json guide shows metadata-based asset declarations. Declare those files with the block rather than loading its styles everywhere without a reason.

6. Optional: use a standalone script module

For a module-based component, WordPress provides wp_enqueue_script_module(). It was introduced in WordPress 6.5, according to its reference checked in November 2026. Modules have their own IDs and dependency declarations. Do not assume a classic-script handle is a module dependency.

This is an alternative experiment, not another initializer for the same component. Replace the main plugin's wpgeared_enqueue_assets() function and its add_action line with the following. Keep the plugin header and guard, and change its Requires at least header to 6.5:

function wpgeared_enqueue_module() {
    if ( ! is_singular( 'post' ) ) {
        return;
    }
    wp_enqueue_script_module(
        'wpgeared-demo-module',
        plugins_url( 'assets/module.js', __FILE__ ),
        array(),
        '1.0.0'
    );
}
add_action( 'wp_enqueue_scripts', 'wpgeared_enqueue_module' );

Create assets/module.js:

export function readyMessage() {
    return 'The module loaded.';
}

document.querySelectorAll('.wpgeared-module-demo').forEach((element) => {
    element.textContent = readyMessage();
});

Use a different test element:

<p class="wpgeared-module-demo">Waiting for the module.</p>

This alternative does not enqueue the original stylesheet or inline configuration. Check that the module changes its own test element's text. Do not leave both versions enabled and then mistake duplicate behavior for a WordPress loading problem.

7. Verify before calling it a performance improvement

With the classic version active, check a single post and an ordinary Page:

  1. On the post, inspect the page source or Network panel for the CSS and JavaScript URLs. Confirm each succeeds and the version is stable across reloads.
  2. Check the emitted script's location and actual defer attribute. Confirm the inline configuration appears before the script.
  3. Confirm the paragraph changes text, the border changes and the browser console has no errors.
  4. On a normal Page, confirm this plugin's assets are absent. Its condition is for the post type, not every singular item such as a Page or Book.
  5. Change the release version after editing an asset, then check the new URL and any remaining page or CDN cache.

For the optional module version, inspect its module tag and test its separate element instead. Browser behavior and successful asset requests are separate from a PHP registry test.

Troubleshoot and undo

The file returns 404: compare the actual folder and filename with the URL. Do not confuse a server path with a public URL.

The file loads but nothing changes: confirm the target element exists, the condition matches the page and the console is clear. Check cached HTML and JavaScript before altering the callback.

The file is missing from the page: verify the plugin is active, the correct hook runs and the theme includes wp_head() and wp_footer().

Another component breaks after asset changes: restore your change. Do not deregister shared dependencies or another plugin's files simply to reduce a request count.

Deactivate this sample plugin and remove its test markup to undo the experiment. Conditional loading can avoid unnecessary requests and execution, but the performance result depends on the site. Measure the relevant pages before and after, and review the broader WordPress speed mistakes before treating one enqueue adjustment as the whole solution.