2

I have a few scripts loading with my theme:

    // loading script.js
    <script type="text/javascript" src="script.js"></script> 

    // doing something using script.js
    <script type="text/javascript"> 
       script-var: <?php echo get_option('script1-var');?>
    </script>

They work well, but when I do wp_enqueue_script instead of <script src=""> the script is loading AFTER in-line js content, so:

     // enqueuing script.js
     wp_enqueue_script('script-js', get_template_directory_uri() ."/scripts/script.js");       

     // doing something using script.js
     <script type="text/javascript"> 
        script-var: <?php echo get_option('script1-var');?>
     </script>

Gives:

  <script type="text/javascript"> 
       script-var: <?php echo get_option('script1-var');?>
  </script>

   <!-- EVERYTHING ABOVE THIS LINE IS USELESS SINCE THE SCRIPT LOADS AFTER, NOT BEFORE, IT -->
  <script type='text/javascript' src='http://address/scripts/script.js?ver=3.2.1'></script>

How to avoid that? I know I could put my inline scripts into different files and enqueue them as well, but this is absolutely pointless since there is a lot of PHP functions in them.

  • I would think having the inline scripts that define your variables printed before the enqueued script would be the desired behavior, isn't it? What are you using those variables for that you don't want them available to the script when it's loaded? – goldenapples Aug 31 '11 at 21:12
  • @goldenapples Well, I have to load the script first to configure it, it works like that for example with Nivo Slider. – Wordpressor Aug 31 '11 at 22:57
0

When you enqueue scripts, they get output with wp_head(), so if you want inline scripts after, put them after wp_head().

However, if you're putting scripts inline just to add some php, a better route would be to enqueue it and use wp_localize_script to set whatever js vars you need from php.

  • Was about to suggest wp_localize_script too, but localized script data gets printed before the scripts as well. – goldenapples Aug 31 '11 at 21:15
  • @Milo, even if localized script data gets printed before the scripts itself I'd love to give it a shot - but I'm not sure how to include PHP data into an array? This does not work: 'foo' => <?php echo get_option('bar');?>. – Wordpressor Aug 31 '11 at 22:59

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.