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?

  • On ACF/Post Save, loop through all your fields there and set which libs are required in a metadata list on the post. Then you only have to check the metavalue of the post later. You could do the same check for shortcodes there as well. – jgraup Nov 6 '16 at 17:14

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.

| improve this answer | |

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 );

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.