DEV3 Technologies home

DEV3 Developer Forum

How do I properly enqueue CSS and JavaScript in WordPress instead of adding tags to header.php?

WordPress helpSolved0 views
dev3 ·

My theme has script and link tags hard-coded in header.php. A plugin loads jQuery twice and my script runs too early. How should assets be loaded?

#wordpress#enqueue#javascript

0

1 reply

dev3 · Accepted answer

Use wp_enqueue_scripts with handles and dependencies. WordPress then orders files, avoids duplicates, and allows versioning and deferral.

add_action( 'wp_enqueue_scripts', function () {
    $ver = wp_get_theme()->get( 'Version' );

    wp_enqueue_style( 'acme-main', get_theme_file_uri( 'assets/main.css' ), array(), $ver );

    wp_enqueue_script(
        'acme-app',
        get_theme_file_uri( 'assets/app.js' ),
        array( 'jquery' ),   // dependencies
        $ver,
        array( 'in_footer' => true, 'strategy' => 'defer' )  // WP 6.3+
    );

    wp_localize_script( 'acme-app', 'ACME', array(
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'acme' ),
    ) );
} );

Notes

  • The fifth argument accepts a boolean (footer) on every version, and an args array with in_footer and strategy (defer or async) since WordPress 6.3.
  • wp_localize_script passes data to JS. For non-translation data, wp_add_inline_script( 'acme-app', 'window.ACME = ' . wp_json_encode( $data ) . ';', 'before' ) is the modern alternative.
  • Admin screens use admin_enqueue_scripts; the login page uses login_enqueue_scripts.
  • Load only where needed: if ( is_page( 'contact' ) ) { ... }.
  • Use get_theme_file_uri() so child themes can override files.
  • Never register your own jQuery copy; depend on 'jquery'. WordPress runs jQuery in no-conflict mode, so use jQuery(...) or wrap code with (function ($) { ... })(jQuery);.

Changing the $ver string forces browsers to fetch a new file after deploy.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.