5

While reading the API page for drupal_add_js, I kept wondering what is the best practice to include inline JavaScript or a JS file.

It seems like it works exactly the same even if you omit 'file', 'external' or 'inline' like in this example :

Without 'file'

drupal_add_js('misc/collapse.js');

With 'file'

drupal_add_js('misc/collapse.js', 'file');

So the question is rather simple. Why would I choose one over another and what is the standard way of coding this ?

Thanks !

9

They are both and the same. The fileparameter you have specified in your second example is the same as the first example as it's the default type.

type: The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults to 'file'.

Source: drupal_add_js

If your question is about whether it's best practice to use inline or file then it depends on your requirements. If you need to load a JavaScript library or a large amount of JavaScript then I would use file type. If you are just loading say some tracking code, or a few lines of JavaScript then I would probably use inline as it's one less HTTP request.

  • Thank you. Since they are the same my question was actually to know what was the best choice for an experienced Drupal developer. It's like indenting with 2 spaces so that any new developer feels "at home" on a project, see ? – vanz Mar 23 '11 at 10:27
  • I tried to answer this in the last paragraph of my answer. Generally inline is used for JavaScript snippets, tracking scripts, etc. File is to be used for loading libraries, large blocks of JavaScript. – Camsoft Mar 23 '11 at 10:30
  • OK, this is not exactly the answer I expected but as it defaults to the proper value I guess there's no better way to answer this. That makes sense. One more thing I found interesting in your answer is the 'inline' thing. On the API page it's written This should only be used for JavaScript that cannot be executed from a file. In my understanding, this wasn't performance related but that's a smart way to use it. Thanks ! – vanz Mar 23 '11 at 10:40
  • Well I guess my answer was not really best practice more my opinion from experience. Though on further reflection as long as you have JS optimisation turn on under performance then the HTTP performance issue I mentioned is no longer an issue as the JavaScripts are combined and cached as a single file and therefore a single HTTP request. Generally you will find tracking code using inline and most other things using file. – Camsoft Mar 23 '11 at 10:46
  • That was my next question. I was just wondering why there would be a HTTP request for this particular file if JS aggregation was turned on. Nice ;-) – vanz Mar 23 '11 at 10:49

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.