1

I am doing some processing in hook_boot since I need that code to run on every page, irrespective of whether or not they are cached.

As a result, jQuery is undefined when I add inline JavaScript to the page.

function hook_boot() {
  drupal_add_js("jQuery('document').ready(function() { //do });");
}

The idea is that we will potentially load a lightbox on every page after processing in hook_boot.

The only way I can see round this is using variable_set and then retrieving that in another hook (e.g hook_node_*). However, that might not be sufficient since we need it to run on every page.

How would you get round this?

3 Answers 3

1

If you add the JavaScript in hook_init, then it will be there the next time the page is served from the cache.

And if the page is served from the cache, then calling drupal_add_js in hook_boot will not add JavaScript to the page, because the page is not assembled from calling the page callback, but is served from the cache.

Use hook_init instead of hook_boot.

2
  • The problem then is that I want to load the JS conditionally, e.g. if(variable_get('show_js', 0)) drupal_add_js(); which isn't possible given that hook_init isn't run on every page.
    – dianovich
    Commented Aug 24, 2011 at 12:56
  • 1
    Clear the cache when the value of the variable changes.
    – Oswald
    Commented Aug 24, 2011 at 14:56
1

I would write a menu hook that replies with "yes, run a function" or "no, don't run a function" (eg, your conditional logic's answer) and is called on every page via ajax. You don't have to worry about expiring your caches that way.

1

You can't have it both ways - if you use the page cache than you lose the ability to deliver a unique response tailored to each visitor.

The answer is usually to serve the same script to all anonymous users, and move the conditional logic into the script itself. If you are switching based on some user action or input, you can store the user data in a cookie or localstorage.

2
  • How would I serve the same script to all anonymous users?
    – dianovich
    Commented Sep 8, 2011 at 8:41
  • You would add the script in hook_init, either unconditionally (for all users), or test using the function user_is_anonymous() if you only want to include it for anonymous users.
    – Dylan Tack
    Commented Sep 8, 2011 at 20:22

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.