The example code you are giving indicates, that you want to have this CSS included on every page. In this case do not bother using #attached
at all and just call drupal_add_css
from hook_page_build
. An even better option is to include the CSS in the module-info file with the following line:
stylesheets[all][] = css/mymodule_default.css
In contrast if the asset is to be added to the page only when a given element is rendered (e.g. a form), then use #attached
on that element. This way the path to the asset gets stored along with the render-array if the element is cacheable. On subsequent page requests, the element will be retrieved from the cache and the asset is attached to the page. If you would use drupal_add_css
together with cacheable elements, the asset would be missing on subsequent page builds.
Note that even when using #attached
, drupal_add_css
is called internally from within drupal_process_attached. The responsible code, but actually boils down to this excerpt:
// Add both the JavaScript and the CSS.
// The parameters for drupal_add_js() and drupal_add_css() require special
// handling.
foreach (array('js', 'css') as $type) {
foreach ($elements['#attached'][$type] as $data => $options) {
// [...]
call_user_func('drupal_add_' . $type, $data, $options);
}
unset($elements['#attached'][$type]);
}
The call_user_func
will invoke either drupal_add_js
and drupal_add_css
respectively, depending the value of $type
. It follows that there is no additional benefit from using #attached
unless the asset is used by a render-array which is to be stored in the cache. Assets specified via #attached
are guaranteed to be loaded if the associated render-array is rendered. They will not be added to the page when the associated render-array is not rendered.
In your specific situation you are attaching the CSS not to an element but to a page region. However the header-region apparently is not rendered by every theme, probably because it is not widely used. The header-region is rendered in page.tpl.php. If a theme chooses to ignore a region, like the Versatile and the Corporate Clean do, the CSS will not be attached.
To sum up:
- Use
#attached
when adding assets to cacheable render-arrays (especially forms and form elements)
- Add stylesheets / scripts to the module-info file or call
drupal_add_js
and drupal_add_css
whenever adding assets globally.
header
region in the theme, thendrupal_render()
would never be called to process this.