如何将javascript移动到drupal的底部页脚

时间:2011-02-05 15:18:22

标签: javascript performance drupal footer

drupal中的性能问题

如何在tpl文件中将javascript移动到底部页脚?

5 个答案:

答案 0 :(得分:4)

在您的主题page.tpl.php中,将print $scripts;行移至页脚。一些模块的JS代码不喜欢这样,但我已经将它与大多数人一起使用了。

http://groups.drupal.org/node/8399

答案 1 :(得分:4)

我刚回答了关于Drupal Answers的类似问题:https://drupal.stackexchange.com/questions/46202/move-aggregated-js-file-to-the-footer/89590#89590

我正在复制粘贴下面的答案以供快速参考。

此外,我不确定问题是否应该迁移到Drupal Answers或合并,否则如果有人有想法请执行此操作或建议如何执行此操作。感谢。


为Drupal 7找到了这个优秀的代码段:https://gist.github.com/pascalduez/1418121

它提供了一种使用$ script和$ head_scripts的方法,以便您可以指定哪些J​​S文件需要进入头部。例如,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');
}

答案 2 :(得分:0)

将所有Drupal的JS移动到页脚的最快方法是在关闭正文标记之前移动$scripts并在 $closure之前移动

在Drupal 6核心内,没有可以轻松检查的选项oder界面。但是在admin/settings/performance下有一个压缩JS文件的选项。建议用于生产。

要将JS文件放到底部,请转到page.tpl.php文件,然后查找<?php print $scripts;?>或类似内容。然后查找$closure;并进行更改:

    <!-- other theme code above -->
    <?php print $scripts; ?>
    <?php print $closure; ?>
    </body> 
</html> 

答案 3 :(得分:0)

答案 4 :(得分:0)

我发现在底部移动

print $scripts
很少有效。大多数情况下,您需要一个解决方案,允许将一些脚本保留在标题中,而其他脚本可以在页脚中移动。

就个人而言,我在template.php中使用drupal_add_js,利用范围选项。

来自Drupal文档:

scope: The location in which you want to place the script.
Possible values are 'header' or 'footer'.
If your theme implements different regions, you can also use these.
Defaults to 'header'.