Skip to content

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 ajax_page_state is added to HTMX requests by Drupal.behaviors.htmxPageState. This 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 script Drupal.behaviors.htmxSwapOob responds to the htmx:oobAfterSwap event to detect and process the inserted JSON, placing the CSS and JS in the appropriate parts of the page.