Attach JavaScript and CSS assets when render entity using Web Sockets Goal:

Attach all the necessary JavaScript and CSS files to the page, when a rendered entity is delivered on a Web Socket event.

Given:


I have a Web Socket with an event when a new entity is created (Via pusher.com but nevermind).
The Web Socket delivers JSON with some meta-data(entity id, created date, title, etc.) and HTML of a single rendered entity.
I catch the event in and render the entity (I do it in JavaScript, client is the same Drupal website).


Problem:

JavaScript and CSS files, needed for rendering, are not attached on the page. (E.g. scripts for display of an image gallery, lazy-loading of images).

My ideas:

I think that I should list all the necessary JavaScript and CSS files (or something like ajax commands, which can attach assets) in the JSON, when I push the event. To achieve this I might need to rendered the entity via some Drupal-AJAX-Renderer.

Afterwards (when I receive the JSON from Web Socket) there should be some way on a Drupal website to attach these files by executing some JavaScript method in Drupal.ajax.

Currently I haven't figured out how to achieve this. Could you give some advice?
It was quite some work to adapt the rendering process. There is a lot of code, I will just summarise the solution. If you want more details, just write a comment.

The solution looks similar to my ideas/hypothesis in the question's description.

I created a custom render which collects all the libraries during rendering in an array. It results in an array:

return [
      'commands' ['An array with ajax commands for settings'],
      'content' =&gt; 'Rendered content(HTML)',
      'libraries' =&gt; 'all the needed assets grouped into libraries',
    ];


I had to to override the AjaxResponseAttachmentsProcessor and AssetResolver classes.

Also I implemented the hook_js_settings_build() to collect all the libraries on the page, as ajaxPageState does not contain all the dependencies.

At the front-end side it is not possible to attach all the assets by comparing ajaxPageState and the response from a Web Socket.