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.
When you enqueue scripts, they get output with
wp_head()
, so if you want inline scripts after, put them afterwp_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.