Dynamic Assets
The Drupal Ajax system adds any new CSS and JS found in the response to the page as it inserts the content. It then attaches any necessary DrupalBehaviors.
We need the same and like core Ajax we need both PHP and JavaScript to process the assets.
Detect, Diff, and Attach
The Drupal property drupalSettings.ajaxPageState.libraries
is added to HTMX requests by
htmxDrupalPageState
which is a handler for the htmx:configRequest
event.
The drupalSettings.ajaxPageState.libraries
property contains the assets already on the page.
All responses to HTMX requests are expected to be HTML. In
\Drupal\htmx\EventSubscriber\HtmxResponseSubscriber::onRespond
we validate
that the request is for HTMX by detecting the HX-Request
header and also
validate that the response is an HtmlResponse
.
The response is passed to \Drupal\htmx\Render\HtmxResponseAttachmentsProcessor
which extends \Drupal\Core\Render\HtmlResponseAttachmentsProcessor
and takes
the data about the additional assets and packages it into a JSON encoded array.
This JSON is added to the response and then appended to the body of the
requesting page by HTMX using hx-swap-oob.
The function htmxDrupalAssetProcessor
responds to the htmx:oobAfterSwap
event to load and process the inserted JSON, placing the CSS and JS in the
appropriate parts of the page.