【发布时间】:2011-06-21 21:55:41
【问题描述】:
drupal 中的性能问题
如何将 javascript 移动到 tpl 文件的底部页脚??
【问题讨论】:
标签: javascript performance drupal footer
drupal 中的性能问题
如何将 javascript 移动到 tpl 文件的底部页脚??
【问题讨论】:
标签: javascript performance drupal footer
在您主题的page.tpl.php 中,将print $scripts; 行移至页脚。一些模块的 JS 代码不喜欢这样,但我已经使用了大多数。
【讨论】:
drupal_add_js 以使用不同的默认 $scope,但修改核心通常是个坏主意。无论如何,您对第三方模块也会有同样的问题,因为它们通常依赖于默认的“标题”。
我刚刚在 Drupal Answers 上回答了一个类似的问题:https://drupal.stackexchange.com/questions/46202/move-aggregated-js-file-to-the-footer/89590#89590
我复制粘贴下面的答案以供快速参考。
另外,我不确定是否应该将问题迁移到 Drupal Answers 或合并,否则如果有人有想法,请执行此操作或建议如何操作。谢谢。
为 Drupal 7 找到了这个出色的代码 sn-p:https://gist.github.com/pascalduez/1418121
它提供了一种拥有 $script 和 $head_scripts 的方法,以便您可以指定哪些 JS 文件需要放在 head 中。例如,Modernizr 应该进入头部脚本。
我将复制粘贴到链接中的解决方案下方,以便将来证明答案。
干杯。
html.tpl.php
<!DOCTYPE html>
<html<?php print $html_attributes; ?>>
<head>
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<?php print $styles; ?>
<?php print $head_scripts; ?>
</head>
<body<?php print $body_attributes;?>>
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $scripts; ?>
<?php print $page_bottom; ?>
</body>
</html>
template.php
// Used in conjunction with https://gist.github.com/1417914
/**
* Implements hook_preprocess_html().
*/
function THEMENAME_preprocess_html(&$vars) {
// Move JS files "$scripts" to page bottom for perfs/logic.
// Add JS files that *needs* to be loaded in the head in a new "$head_scripts" scope.
// For instance the Modernizr lib.
$path = drupal_get_path('theme', 'THEMENAME');
drupal_add_js($path . '/js/modernizr.min.js', array('scope' => 'head_scripts', 'weight' => -1, 'preprocess' => FALSE));
}
/**
* Implements hook_process_html().
*/
function THEMENAME_process_html(&$vars) {
$vars['head_scripts'] = drupal_get_js('head_scripts');
}
【讨论】:
将所有 Drupal 的 JS 移动到页脚的最快方法是将 $scripts 移动到结束正文标记之前和 之前 $closure。
在 Drupal 6 内核中,没有您可以轻松检查的选项或界面。但是在admin/settings/performance 下有一个压缩 JS 文件的选项。推荐用于生产。
要将您的 JS 文件放在底部,请转到您的 page.tpl.php 文件并查找 <?php print $scripts;?> 或类似的东西。然后寻找$closure;并更改它:
<!-- other theme code above -->
<?php print $scripts; ?>
<?php print $closure; ?>
</body>
</html>
【讨论】:
【讨论】:
我发现移动了
print $scripts在底部很少起作用。大多数时候,您需要一个解决方案,允许将一些脚本保留在页眉中,而其他脚本可以移动到页脚中。
来自 Drupal 文档:
scope:您要放置脚本的位置。【讨论】: