Javascript or some else in wordpress header, just after the last header meta tag, before any other css or script: how to

User avatar
axew3
w3all User
w3all User
Posts: 1971
Joined: Fri Jan 22, 2016 5:15 pm
Location: Italy
Contact:

Javascript or some else in wordpress header, just after the last header meta tag, before any other css or script: how to

Post by axew3 »

I was looking around into WordPress core files, after no www searches results about, to check where and how could be possible to inject, x example javascript code, just after latest meta tag, and before any other enqueued (or not enqueued) js file on Wordpress header: i would like also, that this global js var is maybe populated by a WP php value before his output ...

I mean, this kind of scenario: you want a global javascript var, maybe with a specific value, assigned at runtime by WP php, outputted before any other, to have global vars to be used by others scripts.
Could be useful. And possible.
Somebody say it is not possible, or another common answer was: why never you could want something like this?
The reason as said, could be to have a global JS var, available after on any included JS file. May populated by WP php with his value...


So how to add a piece of code like javascript, just after the latest wordpress header meta tag output and before any other (maybe) javascript library, native or not, that you may wish to include, and which you need to load after a global js var, previously declared with his value, may coming from WP php?
this is the way i've do:

Note: use for admin admin_enqueue_scripts
Note: use for front end wp_enqueue_scripts

Code: Select all

function w3all_stp(){
$aval = 'whateveryouwant'; // this will be a global js var
echo "<script type=\"text/javascript\">alert(\"Wow! That's nice!\"); var aJSvar = '".$aval."';</script>"; // wow! this will output before any other script or css, and just after last header meta tag
 wp_register_script('w3all-audiodisplay', plugins_url() . '/js/audiodisplay.js', array(), null, false); // may a script to enqueue ...
//.... more scripts to enqueue, and rendered after! The echo above, will output just after latest meta tag and before any other native or enqueued
 wp_enqueue_script('w3all-audiodisplay');
}
add_action('admin_enqueue_scripts', 'w3all_stp');
This is it. KISS (Keep It Simply Stupid)