-
Notifications
You must be signed in to change notification settings - Fork 5
Enqueue Functions
The am_enqueue_* functions will enqueue an asset with additional attributes based upon its load_method value. Options can be passed in as an array or individual parameters.
// Enqueue a JavaScript asset.
am_enqueue_script(
[
'handle' => 'footer-script',
'src' => 'js/script.js',
'deps' => [],
'condition' => 'global',
'load_method' => 'sync', // 'sync', 'inline', 'async', 'defer'
'version' => '1.0.0',
'load_hook' => 'wp_footer',
]
);Use am_modify_load_method to modify the load method of an already-enqueued script.
// Defer an enqueued JavaScript asset.
am_modify_load_method(
[
'handle' => 'footer-script',
'load_method' => 'defer',
]
);// Load a CSS asset asynchronously.
am_enqueue_style(
[
'handle' => 'site-styles',
'src' => 'css/styles.css',
'deps' => [],
'condition' => 'global',
'load_method' => 'async', // 'sync', 'inline', 'async'
'version' => '1.0.0',
'load_hook' => 'wp_head',
'media' => 'all', // 'print', 'screen', or any valid media query
]
);The am_enqueue_* functions use the same parameters as their core WordPress enqueue equivelant, with the exception of the $in_footer parameter for scripts; use 'load_hook' (details below) instead.
Additional options:
| Name | Description | Default |
|---|---|---|
condition |
The condition for which this asset should load | 'global' |
load_hook |
'wp_head' |
|
— wp_head
|
Load this script via wp_head
|
|
— wp_footer
|
Load this script via wp_footer
|
|
load_method |
'sync' |
|
— sync
|
Use the corewp_enqueue function |
|
— async
|
Adds the async attribute to the enqueue |
|
— defer
|
Adds the defer attribute to the enqueue. Scripts only: deprecated for stylesheets since 2.0.0 and treated as async. |
|
— inline
|
Prints the asset inline in the document head |
deps works the same way it does in core: an asset listed in deps is output before the asset that depends on it, and chains are resolved transitively.
am_enqueue_style(
[
'handle' => 'critical-first',
'src' => 'css/critical-first.css',
'load_method' => 'inline',
]
);
// Printed after `critical-first`, regardless of the order these calls are made in.
am_enqueue_style(
[
'handle' => 'critical-second',
'deps' => [ 'critical-first' ],
'src' => 'css/critical-second.css',
'load_method' => 'inline',
]
);Assets with no dependency between them keep the order they were registered in, so ordering that deps doesn't express is preserved.
A couple of things deps can't do:
-
Pull an asset onto an earlier hook. A dependency that loads on
wp_footercan't be moved up for a dependent onwp_head— that raises anunsafe_load_hookerror instead. -
Order assets it doesn't manage. A dependency on a core handle, or on anything enqueued directly through
wp_enqueue_*, is left to core.