Enqueue script dynamically

I am embedding form using the gravity_form function through a acf gutenberg block.

How can enqueue script dynamically based on the form that is being loaded but make sure its called before wp_head?

If you can predict the form being loaded on a page, you can call gravity_form_enqueue_scripts() to load its scripts and stylesheets in the head correctly. e.g.

The trick is knowing which pages load which forms. I’m not very familiar with ACF, but you should be able to detect which pages have your ACF block by calling has_block() and then perhaps use a little regex to extract the form ID from the page content.

1 Like

But the gravity_form_enqueue_scripts() only works when we put it in header.php [ before wp_head() ]. It’s not working when it’s put in other places for example funtion.php or in any other PHP. The issue is that if I edit the header.php of a theme it will get overwritten the next time the theme updates.

is there any better solution than putting it in header.php?

Read that article on Snippets that I linked above. That explains how you use an action hook to run gravity_form_enqueue_scripts() from anywhere.

You can write a plugin to make your customisations without making modifications to your theme. You can read about writing plugins in the Plugin Handbook: