Nếu theo trang chủ, bạn có nghĩa là trang trước, thì bạn có thể thực hiện hook_preprocess_page()
trong một mô-đun tùy chỉnh.
function mymodule_preprocess_page(&$variables) {
if ($variables['is_front']) {
drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
$variables['scripts'] = drupal_get_js();
}
}
Mã tương tự hoạt động trên Drupal 7, như $variables['is_front']
được đặt trong _template_pre process_default_variables () (được gọi từ template_pre process () ), sử dụng mã sau.
// drupal_is_front_page() might throw an exception.
try {
$variables['is_front'] = drupal_is_front_page();
}
catch (Exception $e) {
// If the database is not yet available, set default values for these
// variables.
$variables['is_front'] = FALSE;
$variables['db_is_active'] = FALSE;
}
Lý do gọi drupal_add_js()
trước, và sau đó drupal_get_js()
là, trong trường hợp một mô-đun khác được thực thi sau sẽ chạy mã sau, tệp JavaScript vẫn sẽ được thêm vào.
function quite_a_different_module_preprocess_page(&$vars) {
drupal_add_js(drupal_get_path('module', 'quite_a_different_mymodule') . '/quite_a_different_module.js');
$vars['scripts'] = drupal_get_js();
}
Sử dụng drupal_add_js()
, tệp sẽ được thêm vào đầu ra được trả về từ drupal_get_js () .