I am using the value of a field in the page as a variable. I am trying to use it in the page somewhere else but I think that there is a problem with the cache because the value is sometimes available and sometimes not.
I have the following:
$elements['#attached']['drupalSettings']['pdf_app_height'] = $password;
and then in a .js file I have:
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.behaviors.pdf_appAccessData = {
attach: function (context) {
value = drupalSettings.pdf_app_height;
alert(value);
window.xx = drupalSettings.pdf_app_height;
}
};
})(jQuery, Drupal, drupalSettings);
The alert (value) always shows the right value but I am using on the page somewhere else the following javascript code:
alert(xx);
Sometimes it is showing the right value and sometimes undefined. Any ideas?
I have seen the answer if we are talking about configuration changes (How do I avoid having to clear the cache when changing a module configuration parameter?) but I don't know how to use it here.
undefined
on JS has actually a value on the server side? On the other hand#attached
is a render array key so if element gets cached you will get the same attached settings every time since the actual element is not rendered again until it's cache is invalidated.$elements['#attached']['drupalSettings']['pdf_app_height'] = $password;
in?alert(drupalSettings.pdf_app_height);
outside of the behavior you get sometimesundefined
but called inside the behavior always returns the proper value? Do you have big_pipe module enabled? If so take in mind that JS are "streamed" to the browser so JS called inside the template could and probably executed first that one attached through the render pipeline.