Non-Blocking Loading Of 3rd Party Scripts In Drupal

Loading JavaScript, especially 3rd party scripts, can block other work happening in the page such as progressive rendering. Imagine the case where including a 3rd party script for ads or social widgets caused your page to load more slowly because of the way these scripts are served by 3rd party services. This type of slow down is common and it has caused some 3rd parties (like Google Analytics) to suggest an alternate method for including their scripts. Let’s examine how to do this with the Drupal JavaScript APIs.

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')[0];
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')[0];
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: