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?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
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?
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
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_enqueue_scripts; the login page uses login_enqueue_scripts.if ( is_page( 'contact' ) ) { ... }.get_theme_file_uri() so child themes can override files.'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.