The WordPress enqueue system

descriptionStandard

I recently made a brief overview of the WordPress enqueue system to act as a quick reference for others.

Here are several simple example on how to use the WP wp_register_script and wp_enqueue_script script system:

$testy_js = '/lib/js/testy_script.js';
wp_register_script( 'testy-example-script', $testy_js, array(), '1.0.0', true );
wp_enqueue_script( 'testy-example-script', true );

Does a script rely on another script being available first:

$testy_js = '/lib/js/testy_script.js';
wp_register_script( 'testy-example-script', $testy_js, array(), '1.0.0', true );
wp_enqueue_script( 'testy-example-script', true );
// The next script loads after 'testy-example-script'
$another_js = '/lib/js/another_script.js';
wp_register_script( 'another-script', $another_js, array('testy-example-script'), '1.0.0', true );
wp_enqueue_script( 'another-script', true );

Require additional inline JS in conjuction with your main script:

$testy_js = '/lib/js/testy_script.js';
wp_register_script( 'testy-example-script', $testy_js, array(), '1.0.0', true );
wp_add_inline_script( 'testy-example-script', 'jQuery(document).ready(function($) {
    // our inline script here
});' );
wp_enqueue_script( 'testy-example-script', true );

Pass values from PHP to your JS script:

$testy_js = '/lib/js/testy_script.js';
wp_register_script( 'testy-example-script', $testy_js, array(), '1.0.0', true );
// Here you can set object attribute value from PHP to access in JS
wp_localize_script( 'testy-example-script', 'testy_vars', array(
    'message' => __( 'This is a test message! Hello!', '' )
) );
wp_enqueue_script( 'testy-example-script', true );

Then in your JS script you can access it via:

jQuery(document).ready(function($) {
let msg = testy_vars.message
    // Additional JS here
});

Hope you enjoy!