Assets
Table of contents
- Overview API
- Using the public API (methods)
There are two main classes delivered:
-
Inpsyde\Assets\Script
- dealing with JavaScript-files. -
Inpsyde\Assets\Style
- dealing with CSS-files.
Each instance requires a string $handle
, string $url
and int $location
.
Overview API
Following configurations are available:
property | type | default | Script | Style | description |
---|---|---|---|---|---|
filePath | string | '' | x | x | optional path which can be set to autodiscover the Asset version |
dependencies | array | [] | x | x | all defined depending handles |
location | int | falls back to Asset::FRONTEND
| x | x | depending on location of the Asset , it will be enqueued with different hooks |
version | string | null | x | x | version of the given asset |
enqueue | bool/callable | true | 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 or StyleHandler::class
| 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]
|
Using the public API (methods)
Versions
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\Style;
$script = new Script('foo', 'www.example.com/script.js');
$script
->withFilePath('/path/to/script.js')
->disableAutodiscoverVersion()
->enableAutodiscoverVersion()
->withVersion('1.0');
$style = new Style('foo', 'www.example.com/style.css');
$style
->withFilePath('/path/to/style.css')
->disableAutodiscoverVersion()
->enableAutodiscoverVersion()
->withVersion('1.0');
Enqueue conditionally
You can enqueue your Assets conditionally by using 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.
Location
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_editor_assets | Frontend and Gutenberg Editor |
Asset::ACTIVATE | activate_wp_head | wp-activate.php |
API
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
.
Using multiple locations
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);
}
);
Dependencies resolving
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');
Automatic resolving of Script dependencies with Webpack
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.
This will not overwrite your existing settings:
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"
Change the Handler
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);
Add Filters
Script
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;
});
Style
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;
});
Localize data
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';
});
Translation data
Scripts can also have translation data via wp_set_script_translations()
. This can be added like following:
<?php
use Inpsyde\Assets\Script;
$script = new Script('foo', 'www.example.com/script.js');
$script->withTranslation('domain', '/path/to/json/file.json');
Script enqueue Footer/Header
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();
Adding inline scripts
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"');
Adding inline styles
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; }');
Adding custom CSS properties
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}
Conditional comments for Script/Style
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]-->
Attributes
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"