I would like to load CSS and JS from https://static.example.com . The typical page contains:

<link rel="stylesheet" href="/sites/default/files/css/css__wBfhyL83sORKzo__AgHv4HOGuOoSbIzIaa4clq9PXs.css?pik02l" media="all" />

and contains similar entries for JS. I would like to add https://static.example.com to the front of the href="URL" for both CSS and JS.

I'm am aware that this can be done with a contrib module. I would like to find a hook or some other way to add this to my custom module.

  • Dis you try adding to your libraries.yml? – Kevin Nov 21 '18 at 22:43

Even though you don't want to use a contrib module I will recommend the CDN module anyways. It does what you want, but if you don't want to use it you can still look at how they do it.

They define a lot of services, but the most interesting one is this one:

    class: Drupal\cdn\File\FileUrlGenerator
    arguments: ['@app.root', '@file_system', '@stream_wrapper_manager', '@request_stack', '@private_key', '@cdn.settings']

The class FileUrlGenerator then does checks for files to determine if they should be rewritten and rewrites them.

| improve this answer | |

These are aggregated assets, so you need to find out how they get added there in the first place. Then you can alter them most likely via hook_page_attachments_alter. Similar to Make canonical URL in document HEAD absolute.

Problematic about this approach is that these assets should are aggregated with that cryptic hash in their name per environment. So you need to switch off your custom module everywhere else except on the live instance.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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