Is it mandatory to enqueue any kind of Javsacript?

I am dynamically generating in a page some Javascript code depending on many conditions, however this happens in the middle of the page. As I have read that as a general rule it’s better to enqueue scripts, I was wondering if this rule applies also to page-specific scripts. For instance:

$var_js = "<script type="text/javascript">// <![CDATA [\n var username; var yearly_programme = {};var monthly_programme = {};var user_role; var timetables = {}; var topbuttons; var middlebuttons_years; var middlebuttons_courses; var bottombuttons; var regelusername; var policies; var regelpass; username="".$wp_username."";user_role="".$role.""; topbuttons=".json_encode($buttons_top)."; middlebuttons_years =".json_encode($buttons_middle_years)."; middlebuttons_courses =".json_encode($buttons_middle_courses)."; bottombuttons=".json_encode($buttons_bottom)."\n// ]]>\n</script>";
echo $var_js;

Is it better to save this string (some variables contain jQuery calls) to a file and enqueue?

For example I could remove the echo and change the above to:

$file = ABSPATH."temp/AH-".$current_user->ID.".js";
file_put_contents($file, $var_js);
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );

What do you think?

1 Answer
1

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.

  1. Separate the dynamically-generated javascript from the static part
  2. In the header, register the static javascript
  3. In the body, generate the dynamically-generated javascript
  4. 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 );
}

Leave a Comment