Lazy load production Angular app files

Public

Drupal wants you to add js / css files you know about. This is fine if it's something like inline.bundle.js. The problem with a production / compiled angular app if your doing headless stuff in Drupal is that the compiled files are things like inline.12i38dhfn2342.bundle.js so that end users get fresh files when there's a legit change to your application.

This code can target either production or development files and ensure they are included the right way in the right order.

Get raw version
php
  1. /**
  2.  * Implements hook_page_build().
  3.  */
  4. function YOURMODULE_page_build(&$page) {
  5. // ensure this is at least in scope of the app
  6. if (arg(0) == 'WHATEVERPATH') {
  7. // a little silly looking probably but this allows us to ensure our Angular app can be
  8. // compiled either into production or development mode and still work correctly either way
  9. $dh = opendir(DRUPAL_ROOT . '/' . drupal_get_path('module', 'YOURMODULE') . '/app/dist');
  10. $items = array();
  11. // open directory and walk through the filenames
  12. while ($file = readdir($dh)) {
  13. // skip directory iterators
  14. if ($file != "." && $file != "..") {
  15. // preg match for files patterned as styles/inline/scripts/vendor/main.hashvalue/or/not.bundle.css/js
  16. if (preg_match('#^(styles|inline|scripts|vendor|main)\.*\.[^\s]+(\.(js|css))#', $file)) {
  17. // figure out the file so we can order them afterwards
  18. $tmp = explode('.', $file);
  19. $key = array_shift($tmp);
  20. // add to our file to the match array because these MUST be in the right order
  21. $items[$key] = drupal_get_path('module', 'YOURMODULE') . '/app/dist/' . $file;
  22. }
  23. }
  24. }
  25. $keys = array('styles', 'inline','scripts','vendor','main');
  26. foreach ($keys as $id => $key){
  27. if (isset($items[$key])) {
  28. if ($key == 'styles') {
  29. drupal_add_css($items[$key]);
  30. }
  31. else {
  32. drupal_add_js($items[$key], array('scope' => 'footer', 'weight' => 1000 + $id));
  33. }
  34. }
  35. }
  36. }
  37. }