How to prevent dynamic library definition from being cached? I have a use case where i want to dynamic add library  , Attributes of library will vary with page. In my case the $callback will be different depending on the page.

$libraries['sample.my-lib'] = [
    'js' => [
      '//maps.googleapis.com/maps/api/js?'.$key.'&amp;callback='.$callback
       => [
        'type' => 'external',
        'attributes' => [
          'async' => "true",
          'defer'=> 'true'
        ],
       ],
    ],
    'weight' => '2200', 
  ];


The above code works but when i navigate to different page i have to clear the cache to get updated value of $callback.

I have tried hook_library_info_alter but library definition is still cached.

How can i work around it to make my use case work.
You could trigger Drupal::service('library.discovery')-&gt;clearCachedDefinitions() every time, but that seems like a painful workaround performance-wise. All library definitions for a particular theme seem to be stored in a single cache entry library_info:$activeTheme, which doesn't allow any more finely grained invalidation.

Would the range of values of "callback" allow you to loop through them and define a separate library for each one you use, and then attach the specific one you need? The JS gets loaded on demand, so only the attached library would appear on each page.

foreach (static::CALLBACKS as $name) {
  $libraries['sample.my-lib.' . $name] = [
    //...
  ];
}


Or maybe it would be possible to call the appropriate callback from a single main function (possibly setting the callback via a drupalSettings attachment), allowing you to put a fixed value in the Google Maps API URL?