[development] An alternative to common thinking in 5->6migration

Daniel F. Kudwien news at unleashedmind.com
Mon Mar 9 17:31:25 UTC 2009

If it makes sense for your use-case, drupal_add_css/_js() should always be
invoked in the builder or rendering function of a "thing".

I.e., if the CSS applies to a form, invoke drupal_add_css() from the form
builder function.  That way, the form (or other "thing") can be rendered
with the proper stylesheet in other places.

However, if your CSS applies specifically to your module's help text, then
yeah, hook_help() is the proper location for invoking drupal_add_css() - so
the help text would be the "thing" here.


> Nancy Wichmann wrote:
> >
> > In moving modules from 5.x to 6.x it is commonly suggested 
> to move our 
> > “drupal_add_css” (and _js/) /into hook_init. Ceratinly I 
> did this in 
> > nearly all my modules because it was the common suggestion. 
> However, 
> > now that I’m making a big change in one and having problems 
> with the 
> > CSS, it dawned on me that this suggestion adds the CSS files to
> > **every** page, not just the ones we were targeting. It 
> finally dawned 
> > on me that I have hook_help that only fires on the pages I 
> need to CSS 
> > on, so I moved the “drupal_add_css” into hook_help, which 
> to me makes 
> > a lot more sense because now my CSS is only applied to 
> those pages for 
> > which it is intended. What do others think of this? Are 
> there pitfalls 
> > I may not have covered?
> >
> To answer your question, with "css munging" drupal_add_css 
> doesn't result in an additional page hit for the new css file 
> (because they are combined into 1) and I normally suggest 
> including it because the small bandwidth penalty on page load 
> #1 is normally outweighed by the latency 
> + bandwidth on the following page loads where it has t be dynamically
> loaded. if you dont use css munging then you approach has 
> some validity i suppose but id be hesitant to put it in the 
> help section and instead makes sure it is added when and 
> where needed by your actual theme code so that it isnt a 
> maintenance issue.
> -mf

More information about the development mailing list