Some of My Preliminary Findings for JavaScript file in SDC

To begin with, I think it is worth mentioning when and how many times is the JavaScript file in the SDC is ran: (* I don’t know if it is just me, I was expecting the JS fiel in the SDC to run as many times as the SDC itself is used, however, it is actually only running once).

TLDR;

  • Attach Point: Druapl attaches the JavaScript in the SDC to its asset library via render array
  • How Many times:

To test this, I have setup this SDC named test-js in a Radix theme with the following files: (see: test-js-sdc-example-files.zip)

1
2
3
4
theme\component\test-js
                  |_______test-js.twig
                  |_______test-js.component.yml
                  |_______test-js.js

The content are as follows:

1
2
3
4
{# [test-js.twig] #}
<div class="test-js opc:p-0 opc:bg-black opc:text-white opc:mb-[2px]!">
  <p class="opc:pb-0! opc:mb-0!">[Test-JS-SDC]: {{ "now"|date("h:i:s.v A") }}</p>
</div>
1
2
3
4
5
# [test-js.component.yml]
$schema: https://git.drupalcode.org/project/drupal/-/raw/10.1.x/core/modules/sdc/src/metadata.schema.json
name: test-js
status: experimental
description: 'The test-js component auto-generated by drupal-radix-cli'
1
2
3
4
5
6
7
8
9
// [test-js.js] 
//          (OR [_test-js.js] when in Radix Theme)
((Drupal) => {
    // Print current time in milliseconds
    console.log(
        '[test-js.js] \t',
        new Date().toLocaleTimeString() + '.' + new Date().getMilliseconds().toString().padStart(3, '0')
    );
})(Drupal);

For quick testing purpose, I then did some editing to the page-content.twig component, to replace the default {{content}} block with a multiple of this test-js SDC component like the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
	{% if page.content %}
    <div class="page__content" id="main-content">
      <div {{ page_content_container_attributes.addClass(page_content_container_classes) }}>
        {% block page_inner_content %}
-            {{ page.content }}
+            <div class="opc:flex opc:flex-row opc:flex-wrap opc:gap-1">
+                {{ include('radix_opc:test-js') }}
+                {{ include('radix_opc:test-js') }}
+                {{ include('radix_opc:test-js') }}
+                {{ include('radix_opc:test-js') }}
+                {# .... #}
+            </div>
        {% endblock %}
      </div>
    </div>

As I was mentioned, I am expected to see multiple of the component in the content area of html, as well as multiple console log [test-js] ...; Though I predicted the multiple of components on html, superizingly the JavaScript file in the SDC only get executed once ! And looking at the network history, it’s triggering point (attach process) seem to be after the theme libraries (such as boostrap.css, popper.js) loads in.

2025-07-18T164350

PENDING POST, NEED TO LOOK INTO THESE POSTS: