The logic of drupal_add_js() is quite good - load misc/drupal.js only when it's needed by another js file.
But what happens when I want to add a js SCRIPT that isn't located inside a file, but needs functions defined in drupal.js? What if all I've got is a small script that creating a unique file for it is a waste?
My solution is patching drupal_add_js(), like that:
function drupal_add_js($file, $nocache = FALSE) {
static $sent = array();
$postfix = $nocache ? '?'. time() : '';
if (!isset($sent['misc/drupal.js'])) {
drupal_set_html_head('<script type="text/javascript" src="'. base_path() .'misc/drupal.js'. $postfix .'"></script>');
$sent['misc/drupal.js'] = true;
}
if (($file != '') && (!isset($sent[$file]))) {
drupal_set_html_head('<script type="text/javascript" src="'. check_url(base_path() . $file) . $postfix .'"></script>');
$sent[$file] = true;
}
}
As you can see, I added a condition to the second if statement that makes it execute only if $file != ''.
Now, if I want to execute my own js script, like adding a load event, I do this inside my theme page template (for example):
drupal_add_js('');
drupal_set_html_head('
<script type="text/javascript">
if (isJsEnabled()) {
addLoadEvent(myfunction);
}
</script>');
What do you think?
Comments
Comment #1
Steven commentedCan already be achieved simply by doing
drupal_add_js('misc/drupal.js');.Comment #2
alonpeer commentedGood solution! Not why didn't I think of that...? =)
Thanks.