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?

2 Answers
2

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.

Leave a Reply

Your email address will not be published. Required fields are marked *