Is it mandatory to enqueue any kind of Javsacript?
Nothing is mandatory, but it is good practice. And since WordPress 4.5 it’s actually quite simple.
Is it better to save this string (some variables contain jQuery calls) to a file and enqueue?
There is no need to write a temporary file just so you can enqueue it. We can now add inline scripts using the wp_add_inline_script()
function.
What do you think?
Here’s what I would do.
- Separate the dynamically-generated javascript from the static part
- In the header, register the static javascript
- In the body, generate the dynamically-generated javascript
- In the footer, enqueue scripts
Both the static javascript and the dynamically-generated script will be placed in the footer, the dynamic script after the static file.
//* Register our script that will contain all javascript
//* that does not need to be dynamically generated
add_action( 'wp_enqueue_scripts', 'wpse_106269_enqueue_script' );
function wpse_106269_enqueue_script() {
wp_register_script( 'wpse_106269', PATH_TO . '/script.js' );
}
//* Dynamically generate some javascript and insert it inline
add_action( 'wp_head', 'wpse_106269_head' );
function wpse_106269_head() {
$js="<script>alert();</script>";
wp_add_inline_script( 'wpse_106269', $js );
}
//* Enqueue our script and inline javascript in the footer
add_action( 'wp_footer', 'wpse_106269_footer' );
function wpse_106269_footer() {
wp_enqueue_script( 'wpse_106269', '', false, false, footer = true );
}