I want to load JavaScript only on the home page of my site. I found this preprocess function but I don't know how to customize it for the home page:

function mytheme_preprocess_maintenance_page(&$variables) {
  $variables['#attached']['library'][] = 'mytheme/cuddly-slider';

I was originally including the library I needed in every page of my site, but I only need it on the home page, so I need to figure this out.

Originally I had it in the .info.yml file like so:

 - 'themename/library'

Any help is appreciated.

2 Answers 2

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') {
        $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
  • 1
    For the front page you could use if ($variables['is_front']). It's already set in theme.inc and it works for other front pages then the frontpage view.
    – 4uk4
    Feb 19, 2017 at 17:52
  • Note that this only works if you use Drupal's default frontpage view. Better use make-me-alive's solution which always works, also when using a node as frontpage.
    – Hudri
    Apr 5, 2018 at 15:12

The other workaround would be using the method from drupal's path matcher interface which returns true if the current page is the front page.

function themename_preprocess_page(&$variables) {

//using the method from the pathmatcherinterface
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $variables['#attached']['library'][] = 'themename/cuddly-slider';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.