3

Is there a way to define a JS library that will use the CDN as a fallback?

Example: Define a billboard.js library that will use the local version of files from libraries directory and fall back to one provided from the CDN otherwise.

There is a possibility to have a check on the JS side and load the libraries from there, yet that does not seem to be the best solution. Another way would be to check if the library is present and then load the ones from CDN. There is a way to either include add the external assets into the render array or to define a standalone billboard-cdn library and make sure that the render array will get that one included if the files are not present.

Is there a standard or suggested approach for achieving just that?

I'm currently looking at doing just that for the h5p_analytics module, where it is currently required to manually install the d3 and c3 library files in order to get them working (as seen from the libraries.yml file). I don't like that approach as it requires a check of the JS side to only display the graphs when the libraries are present. I'm going to replace the now abandoned c3.js with billboard.js and would prefer to make sure that the graphs will be shown in either case, with the ability to use the local version of the library.

Any suggestions are more than welcome as I would really prefer to keep it as simple as possible.

1 Answer 1

3

Use hook_library_info_build to declare the library dynamically and use PHP's file_exists to detect if the local file exists.

2
  • 1
    This module decides to use CDN or local based on a setting, but you can use any PHP logic in this hook: git.drupalcode.org/project/mathjax/-/blob/4.x/…
    – mona lisa
    Sep 16, 2022 at 15:01
  • Thank you. That seems to be a good way to achieve what is needed. I will probably go with an alter hook instead and have two libraries (one that uses local files and one that uses CDN), keep the CDN as a default and switch it to the local version if present: api.drupal.org/api/drupal/…
    – Pjotr
    Sep 16, 2022 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.