External Scripts And Drupal
Drupal includes a option in
drupal_add_js() to include external scripts. The use looks something like:
drupal_add_js('//example.com/foo.js', array('type' => 'external'));
This will include the external script via a standard script tag. Unfortunately, this is blocking in nature. Especially when you look at how Drupal will default this to be included in the header.
An Alternate Method
The recommendation for including most 3rd party scripts is a different method. I say most because there are some scripts that fail when working this way. Be sure to test this for your case but it works most of the time. They style looks like the following snippet I got from Steve Souders blog.
var sNew = document.createElement("script"); sNew.async = true; sNew.src = "http://script/url"; var s0 = document.getElementsByTagName('script'); s0.parentNode.insertBefore(sNew, s0);
Now, we can bring this into Drupal like so…
$js = <<<EOT var sNew = document.createElement("script"); sNew.async = true; sNew.src = "http://script/url"; var s0 = document.getElementsByTagName('script'); s0.parentNode.insertBefore(sNew, s0); EOT; drupal_add_js($js, array('type' => 'inline'));
*Note: be sure to switch out
http://script/url for the url to your script.
If you want to look at background on script loading styles some further reading:
- Loading Scripts Without Blocking
- Google Analytics Asynchronous Tracking: How it works - This has some good details on what happens in the browser.
- Don’t docwrite scripts