Conditionally loading JavaScript based on the Advanced Custom Fields in the post

by jshwlkr   Last Updated July 18, 2018 02:08 AM

I am building a site/theme where post content is authored in a modular way (mostly, but not exclusively) with ACF's flexible content field. These fields could have JavaScript functionality attached to them on the public front-end. You might have an image upload that has parallax applied to it or a text block that has a click or hover animation applied to it, for example. I'm trying to determine the most useful method for conditionally loading the different JavaScript libraries that might power this functionality (in the post, as the public sees it, I'm not talking about the admin side). Specifically I'm trying to avoid always loading everything, instead I'm hoping to load specific libraries based on the fields actually present in the post. Is there an established way, outside of the brute force method of looping through the content multiple times to first check for fields and then later to display them?

Answers 2

I would suggest using the True/False in ACF to determine whether you should load the scripts you are referencing. And create a function for those specific scripts to load them if "True". Something like this...


  if( get_field('true_false_field') ) { 
    add_action( 'wp_enqueue_scripts', 'enqueue_the_script' );

  function enqueue_the_script() {
    wp_enqueue_script( 'my-js', 'filename.js', false );

November 04, 2016 14:49 PM

ACF has finegrained filters for fields when they get loaded.

add_action( 'wp_enqueue_scripts', 'register_my_scripts', 5 );
function register_my_scripts() {
    wp_register_script( 'my-script', 'path-to/my-script.js', array(), 'version', true );

add_filter('acf/load_field/name=my_field_name', 'load_field_my_field_name');
function load_field_my_field_name( $field ) {
    wp_enqueue_script( 'my-script' );
    return $field;

Normally all scripts should be enqueued in wp_enqueue_scripts hook. So you should make sure your script and its dependencies (which haven't been loaded yet) can be loaded in footer. Like this your script gets enqueued when the fields are accessed in the content.

November 05, 2016 17:15 PM

Related Questions

Include 3rd party ACF add-ons with theme

Updated October 12, 2017 19:08 PM

Using ?p=$post_ID instead of permalink in AJAX result

Updated September 02, 2017 16:08 PM

WordPress get_template_part() function not working

Updated August 09, 2016 08:03 AM

Will loading too many ACF Fields cause slow down?

Updated January 15, 2018 20:08 PM