Often you need to load external JavaScript resources into a Drupal page. Unfortunately those can be from external servers that are slow. Even if the servers are fast, it is great to be able to take advantage of Drupal's JavaScript aggregation to make it a single HTTP request for the JavaScript file instead of multiple.
The attached starter module is useful to create a local copy of external JavaScript files.
This is a task that is really site specific. There are visibility rules and lists of modules to maintain. So, rather than creating a contributed module for it I'm presenting it here as a tutorial. You can also download the
code for Drupal 6 as a .tgz.
There are three functions in this starter module.
List out your files in customlocaljs_files
This function is just a piece of configuration to let other functions know which files they are dealing with.
<?php
/**
* A helper function to list all your external js files.
*/
function customlocaljs_files() {
return array(
'example1' => 'http://example.com/number-magic.js',
'exampleb' => 'http://example.com/fun-with-advertising.js',
);
}
?>
Download and Add the JavaScript in customlocaljs_init
This function shouldn't need any tweaks unless you want to modify exactly which pages on the site the JavaScript should be added to.
<?php
function customlocaljs_init() {
// If you want you could also do this in a node_api or wherever it makes sense.
// Only do this in your init if that's where you need to add the js.
$directory = file_directory_path() .'/customlocaljs';
foreach (customlocaljs_files() as $key => $url) {
// First make sure that the file is available locally.
$file_destination = $directory .'/'. basename($url);
if (!file_exists($file_destination)) {
$result = drupal_http_request($url);
if ($result->code == 200) {
// Check that the files directory is writable.
if (file_check_directory($directory, FILE_CREATE_DIRECTORY)) {
file_save_data($result->data, $directory . '/' . basename($url), FILE_EXISTS_REPLACE);
}
}
}
// This actually adds the file to the page.
drupal_add_js($directory .'/'. basename($url));
}
}
}
?>
Delete the files every 24 hours: customlocaljs_cron
The final purpose is to delete the files every 24 hours. This is important since the code that downloads files only goes to get them if they aren't available.
<?php
function customlocaljs_cron() {
// Redownload the files every day.
if (time() - variable_get('customlocaljs_last_cache', 0) >= 60*60*24) {
// You have to create this file locally.
foreach (customlocaljs_files() as $key => $url) {
file_delete(file_directory_path() .'/customlocaljs' . '/' . basename($url));
}
// Clear aggregated JS files.
if (variable_get('preprocess_js', 0)) {
drupal_clear_js_cache();
}
variable_set('customlocaljs_last_cache', $_SERVER['REQUEST_TIME']);
}
}
?>
And that's it!
Once you've done this you should of course make sure that you are running cron and then bask in the glory that is locally aggregated javascript files.