I'm trying to build a custom module https://github.com/alexseif/drupal_infinite_scroll and I need to load the image in the images folder "images/ajax-loader.gif" in the js file alx-infinite-scroll.js

I have this in my js file drupal_get_path('module', 'alx_infinite_scroll') + '/images/ajax-loader.gif' I have no clue where to start, any help would be much appreciated and/or link to the relevant documentation if possible.

  • You've added both Drupal 7 and Drupal 8 tags. The module you linked seems to be only for Drupal 7 so am I right to assume the Drupal 8 tag is a mistake?
    – rooby
    Jan 2, 2018 at 23:58
  • Yes, thank you for pointing that out. I was trying to tag it 7, modules
    – Alex Seif
    Jan 3, 2018 at 12:51

1 Answer 1


drupal_get_path() is a PHP function so you cannot call it in your JS.

To use the result of that function in your JS you would need to call the function in your PHP and then add the output to the JS on the page. You can use Drupal.settings for this. For example:

// Settings to pass to our JS.
$settings = array(
  'loaderImgPath' => drupal_get_path(
  ) + '/images/ajax-loader.gif',
// Add to the JS settings.
drupal_add_js(array('alx_infinite_scroll' => $settings), 'setting');

Then you can use something like this in your JS:

Drupal.behaviors.alxInfiniteScroll = {
  attach: function (context, settings) {
    var imgPath = settings.alx_infinite_scroll.loaderImgPath;

I recommend reading some of the documentation on Drupal's JavaScript APIs as it goes over this. For example: https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

To do that though you need to add the above PHP code somewhere. In your case you are loading your JS in the info file, which means it will load on every page. I would advise against this unless you actually need your JS to run on all pages, but if you do want it on all pages you could use something like hook_page_build().

In that case since you are dealing with the page render array you can use the #attached method of adding JS and JS settings that is referred to on the documentation page I linked above.

  • Thank you very much :) I knew I was writing something wrong, mixing php and js but I couldn't imagine how to get to your answer, I'll give it a go
    – Alex Seif
    Jan 11, 2018 at 17:53

Your Answer

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

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