How to move javascript to footer in drupal

for performance issues in drupal

how to move javascript to footer in tpl file?

+3
source share
5 answers

In your topic, page.tpl.phpmove the line print $scripts;to the footer. Some JS code modules do not like this, but I have worked with most.

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

+4
source

I just answered a similar question on Drupal Answers: https://drupal.stackexchange.com/questions/46202/move-aggregated-js-file-to-the-footer/89590#89590

I will copy the answer below for quick reference.

, , Drupal Answers , , - , , . .


Drupal 7: https://gist.github.com/pascalduez/1418121

$ script $head_scripts, , JS . , 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');
}
+4

Drupal JS - $scripts AND $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> 
0

,

print $scripts
below rarely works. In most cases, you will need a solution that allows you to save some scripts in the header, while others can be moved in the footer.

Personally, I use drupal_add_js in template.php using the scope option.

From the Drupal docs:

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'.
0
source

Source: https://habr.com/ru/post/1790193/


All Articles