Yes, something like that. If block and it's content are loaded in the page (so I guess detect by ID or something) it would load the .js, but if block is not loaded, it wouldn't load the .js.

I need this, because now each time when the block is not loaded, it still always loads the .js from theme in every page no matter what and that code interacts for some reason with other javascript elements like flexslider and it disables it for some reason and etc. Which is bad.

So it should load the .js only when the block is rendered/printed.

1 Answer 1


Depends on what type of block your need the js for. If it's a custom block you created in a module, you can just tack drupal_add_js into the block definition function.

If your trying to add it to a block was created by someone else's module, or drupal created (IE, you didn't create it with a module), you could create a simple module that uses hook_block_view, which is fired whenever a block is loaded. You should be able to check from there if that is the block you want, then use drupal_add_js to load your js from that module.

  • The block is simple custom block. It's not related to any modules. So I have to create custom block now just for all this? I'm not experienced with this. Could you paste in complete custom example codes to make it work please? Sep 2, 2014 at 16:01
  • I used PHP filter and added this piece to block, works perfect. <?php drupal_add_js(path_to_theme() .'/js/validate.js'); ?> Thanks for help, cheers. Sep 2, 2014 at 16:08

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.