3 namespace Drupal\Core\Asset;
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Core\State\StateInterface;
9 * Renders JavaScript assets.
11 class JsCollectionRenderer implements AssetCollectionRendererInterface {
14 * The state key/value store.
16 * @var \Drupal\Core\State\StateInterface
21 * Constructs a JsCollectionRenderer.
23 * @param \Drupal\Core\State\StateInterface $state
24 * The state key/value store.
26 public function __construct(StateInterface $state) {
27 $this->state = $state;
33 * This class evaluates the aggregation enabled/disabled condition on a group
34 * by group basis by testing whether an aggregate file has been made for the
35 * group rather than by testing the site-wide aggregation setting. This allows
36 * this class to work correctly even if modules have implemented custom
37 * logic for grouping and aggregating files.
39 public function render(array $js_assets) {
42 // A dummy query-string is added to filenames, to gain control over
43 // browser-caching. The string changes on every update or full cache
44 // flush, forcing browsers to load a new copy of the files, as the
45 // URL changed. Files that should not be cached get REQUEST_TIME as
46 // query-string instead, to enforce reload on every page request.
47 $default_query_string = $this->state->get('system.css_js_query_string') ?: '0';
49 // Defaults for each SCRIPT element.
51 '#type' => 'html_tag',
56 // Loop through all JS assets.
57 foreach ($js_assets as $js_asset) {
58 // Element properties that do not depend on JS asset type.
59 $element = $element_defaults;
60 $element['#browsers'] = $js_asset['browsers'];
62 // Element properties that depend on item type.
63 switch ($js_asset['type']) {
65 $element['#attributes'] = [
66 // This type attribute prevents this from being parsed as an
68 'type' => 'application/json',
69 'data-drupal-selector' => 'drupal-settings-json',
71 $element['#value'] = Json::encode($js_asset['data']);
75 $query_string = $js_asset['version'] == -1 ? $default_query_string : 'v=' . $js_asset['version'];
76 $query_string_separator = (strpos($js_asset['data'], '?') !== FALSE) ? '&' : '?';
77 $element['#attributes']['src'] = file_url_transform_relative(file_create_url($js_asset['data']));
78 // Only add the cache-busting query string if this isn't an aggregate
80 if (!isset($js_asset['preprocessed'])) {
81 $element['#attributes']['src'] .= $query_string_separator . ($js_asset['cache'] ? $query_string : REQUEST_TIME);
86 $element['#attributes']['src'] = $js_asset['data'];
90 throw new \Exception('Invalid JS asset type.');
93 // Attributes may only be set if this script is output independently.
94 if (!empty($element['#attributes']['src']) && !empty($js_asset['attributes'])) {
95 $element['#attributes'] += $js_asset['attributes'];
98 $elements[] = $element;