I have a block with invocation code inside(it invokes js code from OpenX ads server), my site is responsive and this block get cloned(with jquery .clone() function) on ipad or iphone version of the site. So to avoid calling the invocation js code 2 times i need to set js variable (like this - > window.isScriptLoaded = FALSE) and then inside my block i can easy do next thing:

if (window.isScriptLoaded == FALSE) {
    window.isScriptLoaded = TRUE;
    //invocation code...

in this case all working fine, i can easy add this variable to any js file in drupal.

But in my case admin can add new block and insert new invocation code - SO I need to generate window.isScriptLoaded2 and output this variable BEFORE code in block is loaded

i tried next thing

function HOOK_page_alter(&$page) {
  //get all the variables
  //i generate my variables in database
  $var = db_query("SELECT * FROM {banners}")->fetchAll();
     $full_array = array();
     foreach($var as $object) {
         //for example Anyvariable = FALSE;
         $array[$object->name] = $object->value;
      drupal_add_js(array('common' => array(
    'vars' => $array,
    )), 'setting');


this works but, code in block is loaded before drupal.settings.vars.Anyvariable is loaded. So my variables is always false


It is also hard to say if this will work without seeing exactly what you need to do, but you may want to play with the scope, group, and weight options for drupal_add_js(). These may help you get the order that you need. From the docs

The exact ordering of JavaScript is as follows:

  • First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by the theme.
  • Then by group.
  • Then by the 'every_page' flag, with TRUE coming before FALSE.
  • Then by weight.
  • Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal_add_js() that happened later in the page request gets added to the page after one for which drupal_add_js() happened earlier in the page request.

When I have been in similar situations, I implement a template_preprocess_html(), create some markup, stuff it into $variables, and then output this before the print $scripts in html.tpl.php I have to use this in some very specific situations where I need to output JS very early in the <head> before CSS and JS is loaded.

| improve this answer | |
  • oh my god, this task is pissed me off, thank you (^_^;) i generated variable in preprocess_html and used it before $scripts ITS TRUE u made my day <3 – Petro Popelyshko Feb 4 '13 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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