DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

How to Use wp_enqueue_scripts to Load CSS and JS in WordPress

A complete guide to loading WordPress CSS and JavaScript with wp_enqueue_scripts, including enqueue arguments, dependencies, cache versions, conditional assets, loading strategies, modules and fixes for missing files.
WorldWordPress Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the wp_enqueue_scripts action for assets that belong on the public-facing part of a WordPress site. Attach one callback to that hook, then call wp_enqueue_style() for CSS and wp_enqueue_script() for JavaScript inside the callback. WordPress uses the handles, dependencies, versions and loading settings you provide to generate the correct tags and order the files.

The same pattern works for a game site, a blog, or any other theme: keep front-end assets in the front-end hook, load only what a request needs, and verify that the active theme prints wp_head() and wp_footer().

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What wp_enqueue_scripts does

wp_enqueue_scripts is an action hook, not an enqueue function itself. It gives your code a reliable point during a front-end request to declare stylesheets and scripts. The WordPress Developer Resources hook reference describes it as “the proper hook to use when enqueuing scripts and styles that are meant to appear on the front end.”

When your callback runs, WordPress records each asset by its handle. Later, the system prints the required CSS link and JavaScript tags in the document head or footer, resolves registered dependencies, and applies the version and loading options you selected. Calling the functions directly in a template can work in limited cases, but it bypasses the central dependency and conditional-loading system and is harder to maintain.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Where the callback belongs

In a classic theme, put the callback and its add_action() call in the theme’s PHP code, normally functions.php or a file that the theme includes. A plugin can use the same hook when it owns front-end assets. The important part is that the code is loaded before the hook fires and that the callback is attached exactly once.

Use the correct context hook

Where the asset appears Hook Typical use
Public-facing pages wp_enqueue_scripts Theme styles, interactive menus, game galleries and other visitor-facing features
WordPress administration screens admin_enqueue_scripts Editor or settings-page CSS and JavaScript
Login screen login_enqueue_scripts Branding or behavior on the login form

An admin stylesheet enqueued on wp_enqueue_scripts will not become an admin-screen asset merely because the file is valid. Select the hook that matches the document being rendered.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A minimal theme implementation

This complete example loads one stylesheet and one script on every front-end request handled by the theme:

<?php
function mytheme_enqueue_assets() {
    wp_enqueue_style(
        'mytheme-main',
        get_parent_theme_file_uri( 'assets/css/main.css' ),
        array(),
        wp_get_theme()->get( 'Version' ),
        'all'
    );

    wp_enqueue_script(
        'mytheme-main',
        get_parent_theme_file_uri( 'assets/js/main.js' ),
        array(),
        wp_get_theme()->get( 'Version' ),
        array(
            'strategy'  => 'defer',
            'in_footer' => true,
        )
    );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_assets' );

The handle is the first argument in both calls. The source uses a theme file URL helper instead of a hard-coded domain, so the same code follows a site when its domain or installation path changes. The theme’s declared version is passed to both assets, giving browsers a new query-string value when the theme version changes.

Keep each handle unique within the page. A slug such as mytheme-main makes collisions with another theme or plugin much less likely than a generic name such as main.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Understanding the enqueue arguments

Stylesheet arguments

Argument Purpose Practical guidance
Handle Unique identifier for the stylesheet Prefix it with your theme or plugin slug, for example mytheme-main.
Source Asset URL, or a path interpreted relative to the WordPress root Use a theme URL helper such as get_parent_theme_file_uri() rather than embedding the site’s domain.
Dependencies Array of registered style handles that must be available first Pass array() when the file has no prerequisites.
Version Value appended to the generated URL for cache management Use an explicit release or build version, the theme version, false, or null according to the caching behavior you need.
Media Media condition for the stylesheet The default is all; values can include screen, print, or a media query.

A print-only file, for example, should use print rather than loading as a screen stylesheet. A responsive condition can be supplied as a media query string when the browser should apply the file only at matching viewport conditions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Script arguments

The first four arguments of wp_enqueue_script() follow the same handle, source, dependency and version model. The fifth argument is an arguments array in modern WordPress versions:

Option Effect When to choose it
in_footer Requests output in the footer instead of the head Useful for code that does not need to run before the page body is parsed.
strategy => 'defer' Allows downloading while parsing while delaying execution until parsing is complete A sensible default for many independent front-end scripts that should preserve document order.
strategy => 'async' Allows downloading and execution independently of document parsing and other scripts Use only when the script does not depend on DOM order or another script’s execution.

in_footer and a loading strategy solve different problems. Footer placement changes where the tag is printed. defer and async change how the browser fetches and executes it. If a script depends on another script, declare that dependency and avoid an execution mode that would allow the dependent file to run first.

Enqueue directly or register first

Direct enqueue

When a file is needed immediately, call wp_enqueue_script() or wp_enqueue_style() with its source. For scripts, supplying a source registers the handle and enqueues it in one operation. This is the shortest form for a global theme asset.

Register, then enqueue conditionally

Use wp_register_script() when you want to define an asset once but decide later whether a page needs it. Registration records the source, dependencies and version without requesting output. A later wp_enqueue_script( 'handle' ) can enqueue the registered definition, and another script can list that handle as a dependency.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
<?php
function mytheme_register_assets() {
    wp_register_script(
        'mytheme-gallery',
        get_parent_theme_file_uri( 'assets/js/gallery.js' ),
        array(),
        wp_get_theme()->get( 'Version' ),
        array(
            'strategy'  => 'defer',
            'in_footer' => true,
        )
    );
}
add_action( 'wp_enqueue_scripts', 'mytheme_register_assets' );

function mytheme_enqueue_gallery_assets() {
    if ( is_page( 'gallery' ) ) {
        wp_enqueue_script( 'mytheme-gallery' );
    }
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_gallery_assets' );

In this pattern the handle is registered before the conditional callback tries to enqueue it. If an enqueued script lists a registered dependency, WordPress includes that dependency automatically and places it before the dependent script.

Declare dependencies to guarantee load order

Dependencies are handle names, not file paths. Every name in the dependency array must already be registered. WordPress resolves the graph and outputs prerequisites before the asset that needs them.

<?php
wp_register_script(
    'mytheme-controls',
    get_parent_theme_file_uri( 'assets/js/controls.js' ),
    array(),
    wp_get_theme()->get( 'Version' ),
    array( 'in_footer' => true )
);

wp_enqueue_script(
    'mytheme-game-ui',
    get_parent_theme_file_uri( 'assets/js/game-ui.js' ),
    array( 'mytheme-controls' ),
    wp_get_theme()->get( 'Version' ),
    array(
        'strategy'  => 'defer',
        'in_footer' => true,
    )
);

Here mytheme-game-ui declares that it needs mytheme-controls. Do not put a filename such as controls.js in the dependency array; it will not be resolved as a registered handle. An unresolved dependency can prevent the dependent asset from being output, so a missing dependency is one of the first things to check when a script disappears.

Load assets only on the requests that need them

Keep the callback on wp_enqueue_scripts, then put conditionals inside it. This preserves the correct front-end lifecycle while avoiding unnecessary downloads on unrelated pages.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common conditional checks

  • is_page() for a page or page set.
  • is_singular() for singular content requests.
  • A custom-template check when an asset belongs to one template.
<?php
function mytheme_enqueue_assets() {
    wp_enqueue_style(
        'mytheme-main',
        get_parent_theme_file_uri( 'assets/css/main.css' ),
        array(),
        wp_get_theme()->get( 'Version' ),
        'all'
    );

    if ( is_singular() ) {
        wp_enqueue_script(
            'mytheme-comments-ui',
            get_parent_theme_file_uri( 'assets/js/comments-ui.js' ),
            array(),
            wp_get_theme()->get( 'Version' ),
            array(
                'strategy'  => 'defer',
                'in_footer' => true,
            )
        );
    }
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_assets' );

Place the condition around the enqueue call, not around the hook registration. This keeps the callback available on every front-end request and lets WordPress evaluate the request context before deciding whether to print the optional file.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Version values and cache invalidation

The version argument controls the URL value WordPress associates with an asset. An explicit version is useful when you know exactly which release or build produced the file. Passing the active theme version, as in the minimal example, ties cache invalidation to theme releases.

Version value Documented behavior Use it when
Explicit string or number That value is used for the asset version query string You publish a deliberate asset or build version.
false Uses the installed WordPress version You intentionally want the WordPress version to control the value.
null Omits the version query string Your delivery layer supplies cache identity elsewhere and you specifically do not want a query string.

Changing a file without changing its version can leave visitors with an old browser or proxy cache. Conversely, a changing version on every request defeats caching. Choose a stable value for a given build and change it when the file’s contents change.

Build-generated metadata

Build tools can create an *.asset.php file containing dependencies and version values. Pass those generated values into the enqueue function instead of maintaining a second, manually edited dependency list. That keeps the metadata used by WordPress aligned with the compiled JavaScript.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
$asset = include get_parent_theme_file_path( 'assets/js/game-ui.asset.php' );

wp_enqueue_script(
    'mytheme-game-ui',
    get_parent_theme_file_uri( 'assets/js/game-ui.js' ),
    $asset['dependencies'],
    $asset['version'],
    array(
        'strategy'  => 'defer',
        'in_footer' => true,
    )
);

The exact path to the generated file must match your build output. If the file is absent or its keys do not match the generated artifact, fix the build or path rather than silently replacing the metadata with an unrelated dependency list.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choosing footer placement, defer and async

A script placed in the footer is printed near the end of the document, provided the theme calls wp_footer(). This often keeps parsing focused on the page content. The defer strategy lets the browser fetch while parsing but delays execution until parsing has finished; deferred classic scripts preserve their relative order. The async strategy allows each file to execute as soon as it is ready, so relative order is not a safe assumption.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

A practical decision rule

  • Use footer placement when the script can wait until the document body has been emitted.
  • Use defer for ordered scripts that need the DOM but should not block parsing.
  • Use async only for genuinely independent code, such as a file that neither depends on another enqueued script nor exposes functions that later files must call.

Do not add async to a dependency chain simply to make the page appear faster. If the dependent file executes first, initialization errors can result even though both files downloaded successfully.

JavaScript modules in WordPress 6.5 and later

For JavaScript modules, use wp_enqueue_script_module() on WordPress 6.5 and later rather than treating a module as an ordinary classic script. Modules have their own dependency and import-map behavior. Keep classic files on wp_enqueue_script() and use the module API for code written to use JavaScript module imports.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not assume that adding strategy => 'defer' to a classic enqueue converts it into a module. Loading strategy and module semantics are separate concerns. Decide first whether the file is classic or modular, then use the corresponding WordPress API and test the generated markup in the target WordPress version.

Why an enqueued file is not loading

Work through these checks in order. Each one eliminates a common failure without changing unrelated code.

  1. Verify the context hook. Front-end assets must be attached to wp_enqueue_scripts. Move admin-only code to admin_enqueue_scripts and login-only code to login_enqueue_scripts.
  2. Confirm the callback runs. Check that the file containing the function is loaded and that add_action( 'wp_enqueue_scripts', 'your_callback' ) is executed. A typo in the callback name or an include that never runs prevents every enqueue inside it.
  3. Check the handle. Use a unique, predictable handle. If another component already registered that handle, WordPress does not replace the existing registration’s parameters when you try to register it again. Rename the handle or adjust the original registration.
  4. Check the source URL. Inspect the generated URL and open it directly. Confirm the path points to the intended theme or plugin file and that the file is deployed at that path.
  5. Check every dependency. Dependency arrays must contain registered handles. A missing registration can stop the dependent asset from being printed.
  6. Check theme output hooks. The active theme must call wp_head() in the document head and wp_footer() before the closing body tag for normal queued output. If either call is missing, the corresponding assets may never appear.
  7. Inspect the final HTML. View the page source or the Elements panel and search for the handle’s URL. The absence of a tag points to registration, conditions or output hooks; a present tag with a failing request points to the URL or deployment.
  8. Use the network panel. Confirm the request status, the version query string, and the order in which dependent scripts load. A 404 identifies a path problem; a successful request followed by a JavaScript error usually points to execution order, a module/classic mismatch, or code inside the file.
  9. Check the conditional branch. Temporarily verify the request type against is_page(), is_singular() or the custom-template test. The asset may be correctly enqueued but intentionally excluded on the page being tested.

A maintainable asset layout

For a small theme, one callback can enqueue the global stylesheet and script, then add a few conditional blocks. For a larger theme, split registration and conditional enqueueing into focused functions, but keep the public-facing hook consistent. Use a naming convention such as mytheme- for every handle and keep source files in predictable directories such as assets/css and assets/js.

Register shared libraries once, then make feature scripts depend on their handles. Register optional feature files without enqueuing them globally. This gives each page a small, explicit asset set while preserving WordPress’s dependency resolution.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Example: global plus feature-specific assets

<?php
function mytheme_enqueue_assets() {
    $version = wp_get_theme()->get( 'Version' );

    wp_enqueue_style(
        'mytheme-main',
        get_parent_theme_file_uri( 'assets/css/main.css' ),
        array(),
        $version,
        'all'
    );

    wp_register_script(
        'mytheme-map',
        get_parent_theme_file_uri( 'assets/js/map.js' ),
        array(),
        $version,
        array(
            'strategy'  => 'defer',
            'in_footer' => true,
        )
    );

    if ( is_page( 'map' ) ) {
        wp_enqueue_script( 'mytheme-map' );
    }
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_assets' );

The global stylesheet is always available, while the map script is emitted only for the page that needs it. If the page slug changes, update the conditional to match the site’s actual routing rule rather than leaving the old condition in place.

Final implementation checklist

  • Use wp_enqueue_scripts for front-end CSS and JavaScript.
  • Attach one callback and keep enqueue calls inside it.
  • Give every asset a unique, prefixed handle.
  • Use theme URL helpers instead of hard-coded site URLs.
  • List registered handles as dependencies, never filenames.
  • Choose a stable explicit, theme, or build version; use false and null only for their documented behaviors.
  • Use in_footer, defer and async according to execution requirements, not as interchangeable switches.
  • Use conditional checks inside the callback for page-specific files.
  • Use wp_enqueue_script_module() for modules on WordPress 6.5 and later.
  • Confirm wp_head() and wp_footer() exist in the active theme.
  • Inspect generated HTML and the browser network panel before changing working code.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.