| nav_order | 4 |
|---|
{: .no_toc }
{: .no_toc .text-delta }
- TOC {:toc}
There are three main classes delivered:
Inpsyde\Assets\Script- dealing with JavaScript-files.Inpsyde\Assets\ScriptModule- dealing with WordPress 6.5+ Script Modules (ES6 modules).Inpsyde\Assets\Style- dealing with CSS-files.
Each instance requires a string $handle, string $url and int $location.
Following configurations are available:
| property | type | default | Script |
ScriptModule |
Style |
description |
|---|---|---|---|---|---|---|
| filePath | string | '' |
x | x | x | optional path which can be set to autodiscover the Asset version |
| dependencies | array | [] |
x | x | x | all defined depending handles |
| location | int | falls back to Asset::FRONTEND |
x | x | x | depending on location of the Asset, it will be enqueued with different hooks |
| version | string | null |
x | x | x | version of the given asset |
| enqueue | bool/callable | true |
x | x | x | is the asset only registered or also enqueued |
| data | array/callable | [] |
x | x | additional data assigned to the asset via WP_Script::add_data or WP_Style::add_data |
|
| filters | callable[] | [] |
x | x | an array of Inpsyde\Assets\OutputFilter or callable values to manipulate the output |
|
| handler | string | ScriptHandler::class, StyleHandler::class, ScriptModuleHandler::class |
x | x | x | The handler which will be used to register/enqueue the Asset |
| attributes | array | [] |
x | x | Allows to set additional attributes to the script- or link-tag |
|
| media | string | 'all' |
x | type of media for the Style |
||
| localize | array | [] |
x | localized array of data attached to Script |
||
| inFooter | bool | true |
x | defines if the current Script is printed in footer |
||
| inline | array | [] |
x | allows you to add inline scripts to Script-class via ['before' => [], 'after' => []] |
||
| translation | array | [] |
x | Load translation for Script-class via ['path' => string, 'domain' => string] |
The version can be set in different ways and even autogenerated based on the file time. Following is possible:
| version | autodiscover | returns | note |
|---|---|---|---|
null (default) |
true (default) |
filemtime | the default behavior |
null (default) |
false |
null |
no version in WP is used |
'1.2.3' |
true / false |
'1.2.3' |
|
'' |
true / false |
current WP version |
<?php
use Inpsyde\Assets\Script;
use Inpsyde\Assets\ScriptModule;
use Inpsyde\Assets\Style;
$script = new Script('foo', 'www.example.com/script.js');
$script
->withFilePath('/path/to/script.js')
->disableAutodiscoverVersion()
->enableAutodiscoverVersion()
->withVersion('1.0');
$module = new ScriptModule('@my-plugin/module', 'www.example.com/module.js');
$module
->withFilePath('/path/to/module.js')
->disableAutodiscoverVersion()
->enableAutodiscoverVersion()
->withVersion('1.0')
->withData(['key' => 'value']);
$style = new Style('foo', 'www.example.com/style.css');
$style
->withFilePath('/path/to/style.css')
->disableAutodiscoverVersion()
->enableAutodiscoverVersion()
->withVersion('1.0');You can enqueue your Assets conditionally by using the following API:
<?php
use Inpsyde\Assets\Script;
use Inpsyde\Assets\Style;
$script = new Script('foo', 'www.example.com/script.js');
$script->canEnqueue(true);
$style = new Style('foo', 'www.example.com/style.css');
$style->canEnqueue(function(): bool {
return is_admin();
});By default, Assets are always enqueued.
By default, the package comes with predefined locations of assets:
| const | hook | location |
|---|---|---|
Asset::FRONTEND |
wp_enqueue_scripts |
Frontend |
Asset::BACKEND |
admin_enqueue_scripts |
Backend |
Asset::LOGIN |
login_enqueue_scripts |
wp-login.php |
Asset::CUSTOMIZER |
customize_controls_enqueue_scripts |
Customizer |
Asset::CUSTOMIZER_PREVIEW |
customize_preview_init |
Customizer Preview |
Asset::BLOCK_EDITOR_ASSETS |
enqueue_block_editor_assets |
Gutenberg Editor |
Asset::BLOCK_ASSETS |
enqueue_block_assets |
Frontend and Gutenberg Editor |
Asset::ACTIVATE |
activate_wp_head |
wp-activate.php |
Location can be set either in constructor directly or via methods:
<?php
use Inpsyde\Assets\Script;
use Inpsyde\Assets\Style;
use Inpsyde\Assets\Asset;
$script = new Script('foo', 'www.example.com/script.js', Asset::FRONTEND);
// overwrite location from constructor
$script->forLocation(Asset::BACKEND);
$style = new Style('foo', 'www.example.com/style.css');
$style->forLocation(Asset::FRONTEND);The default location is Asset::FRONTEND.
To avoid duplicated registration of Assets in different locations such as backend and frontend, it is possible to add
multiple ones via bitwise operator | (OR).
Here's a short example for a Style which will be enqueued in frontend and backend:
<?php
use Inpsyde\Assets\AssetManager;
use Inpsyde\Assets\Style;
use Inpsyde\Assets\Asset;
add_action(
AssetManager::ACTION_SETUP,
function(AssetManager $assetManager) {
$style = new Style('foo', 'www.example.com/style.css', Asset::BACKEND | Asset::FRONTEND );
// or
$style = new Style('foo', 'www.example.com/style.css');
$style->forLocation(Asset::BACKEND | Asset::FRONTEND);
$assetManager->register($style);
}
);Adding an Asset with dependencies can be done like following:
use Inpsyde\Assets\Script;
use Inpsyde\Assets\Style;
use Inpsyde\Assets\Asset;
$script = new Script('foo', 'www.example.com/script.js', Asset::FRONTEND);
$script->withDependencies('wp-elements', 'wp-core', 'wp-i18n');
$style = new Style('foo', 'www.example.com/style.css');
$style->withDependencies('wp-elements');The Inpsyde\Assets\Script-class has support for resolving dependencies and version which are generated
by dependency-extraction-webpack-plugin
.
This Webpack-Plugin will create an additional {fileName}.assets.json or {fileName}.assets.php-file which contains an
array of dependencies parsed out of your JavaScript-file and a version string. To use that feature you can use
following:
script.assets.json
{
"dependencies": [
"foo",
"bar",
"baz"
],
"version": "1234567"
}<?php
use Inpsyde\Assets\Script;
use Inpsyde\Assets\Asset;
$script = new Script('foo', 'www.example.com/script.js');
$script
->forLocation(Asset::FRONTEND)
->withFilePath('/path/to/script.js');
$script->dependencies(); // ["foo", "bar", "baz"]
$script->version(); // "1234567"Based on your Asset::filePath the Script automatically searches in the same folder for {fileName}.assets.json|php
and will load the data.
script.assets.php
<?php
return [
"dependencies" => ["foo", "bar", "baz"],
"version" => "1234567"
];<?php
use Inpsyde\Assets\Script;
use Inpsyde\Assets\Asset;
$script = new Script('foo', 'www.example.com/script.js');
$script
->forLocation(Asset::FRONTEND)
->withVersion('1.0')
->withDependencies("some", "other", "dependencies")
->withFilePath('/path/to/script.js');
$script->dependencies(); // ["foo", "bar", "baz", "some", "other", "dependencies"]
$script->version(); // "1.0"It is possible to change for an Asset the Handler like following:
<?php
use Inpsyde\Assets\Script;
use Inpsyde\Assets\Handler\ScriptHandler;
$script = new Script('foo', 'www.example.com/script.js');
$script->useHandler(ScriptHandler::class);Scripts are having the following filters available:
<?php
use Inpsyde\Assets\Script;
use Inpsyde\Assets\OutputFilter\AsyncScriptOutputFilter;
$script = new Script('foo', 'www.example.com/script.js');
$script
->withFilters(AsyncScriptOutputFilter::class)
->useDeferFilter() // shortcut
->useAsyncFilter() // shortcut
->useInlineFilter() // shortcut
->withFilters(function(string $html, Asset $asset): string {
// your custom filter
return $html;
});Styles are having following filters available:
<?php
use Inpsyde\Assets\Style;
use Inpsyde\Assets\Asset;
use Inpsyde\Assets\OutputFilter\AsyncStyleOutputFilter;
$style = new Style('foo', 'www.example.com/style.css');
$style
->withFilters(AsyncStyleOutputFilter::class)
->useAsyncFilter() // shortcut to above method
->useInlineFilter() // shortcut
->withFilters(function(string $html, Asset $asset): string {
return $html;
});Scripts can have localized data via wp_localize_script(), which can be added like following:
<?php
use Inpsyde\Assets\Script;
$script = new Script('foo', 'www.example.com/script.js');
$script
->withLocalize('foo', ['multiple values'])
->withLocalize('bar', static function(): string {
return 'other value';
});Scripts can also have translation data via wp_set_script_translations(). This can be added like the following:
<?php
use Inpsyde\Assets\Script;
$script = new Script('foo', 'www.example.com/script.js');
$script->withTranslation('domain', '/path/to/json/file.json');To enqueue a script in header or footer - default is "footer" - we have following API available:
<?php
use Inpsyde\Assets\Script;
$script = new Script('foo', 'www.example.com/script.js');
$script
->isInFooter()
->isInHeader();To add inline scripts via wp_add_inline_script() to your Script, you can use following:
<?php
use Inpsyde\Assets\Script;
$script = new Script('foo', 'www.example.com/script.js');
$script
->appendInlineScript('var foo = "bar";')
->prependInlineScript('var baz = "bam"');To add inline styles via wp_add_inline_style() to your Style, you can use following:
<?php
use Inpsyde\Assets\Style;
$style = new Style('foo', 'www.example.com/style.css');
$style->withInlineStyles('body { background-color: #000; }');To add custom CSS properties (CSS vars) you can use following API on your Style:
use Inpsyde\Assets\Style;
$style = new Style('foo', 'www.example.com/style.css');
$style->withCssVars('.some-element', ['white' => '#fff', 'black' => '000']);
$style->withCssVars(':root', ['grey' => '#ddd']);The StyleHandler will automatically check if there are CSS vars available via Style::cssVars() and add them via wp_add_inline_style() to your handle.
Note: Registered CSS vars will be automatically prefixed with -- if not present. The example from above will generate following output:
.some-element{--white:#fff;--black:#000}
:root{--grey:#ddd}Styles and Script can be wrapped into Conditional comments. To do so, you can use following:
<?php
use Inpsyde\Assets\Script;
use Inpsyde\Assets\Style;
$script = new Script('foo', 'www.example.com/script.js');
$script->withCondition('gt IE 9'); // <!--[if gt IE 9]><script src="www.example.com/script.js"></script><![endif]-->
$style = new Style('foo', 'www.example.com/style.css');
$style->withCondition('lt IE 9'); // <!--[if lt IE 9]><script src="www.example.com/style.css"></script><![endif]-->Allows you to set additional attributes to your script- or link-tag like following:
<?php
use Inpsyde\Assets\Style;
use Inpsyde\Assets\Script;
$script = new Script('my-handle', 'script.js');
$script->withAttributes(
[
'async' => true,
'data-value' => 'key',
'nonce' => wp_create_nonce()
]
);
// <script src="script.js" id="my-handle-js" async data-value="key" nonce="{generated nonce}"></script>
$style = new Style('my-handle', 'style.css');
$style->withAttributes(
[
'data-value' => 'key',
'nonce' => wp_create_nonce()
]
);
// <link rel="stylesheet" href="style.css" id="my-handle-css" data-value="key" nonce="{generated nonce}" />Existing attributes like "src" or "id" are not overwriteable. The Inpsyde\Assets\OutputFilter\AttributesOutputFilter only sets attributes which are not already existent on the html-tag. This will not work:
<?php
use Inpsyde\Assets\Script;
$script = new Script('my-handle', 'script.js');
$script->withAttributes(['src' => 'another-script.js']); // Will not overwrite "script.js"WordPress 6.5 introduced Script Modules for native JavaScript ES6 modules. The ScriptModule class provides basic asset management with the following limitations:
Scripts Modules allow sharing data from the server to the client via a filter "script_module_data_{$handle}".
Assets registered as ScriptModule can have shared data added like following:
$module = new ScriptModule('@my-plugin/main', 'assets/main.js');
$module->withData([
'apiUrl' => get_rest_url(),
'nonce' => wp_create_nonce('wp_rest'),
]);use Inpsyde\Assets\ScriptModule;
use Inpsyde\Assets\Asset;
// Basic script module
$module = new ScriptModule('@my-plugin/main', 'assets/main.js');
$assetManager->register($module);
// With dependencies
$module = new ScriptModule('@my-plugin/interactive', 'assets/interactive.js', Asset::FRONTEND)
->withDependencies('@wordpress/interactivity')
->withVersion('1.0.0');WordPress core is actively developing Script Module functionality. Compatibility for these features will most likely be added in later releases.