Skip to content

Instantly share code, notes, and snippets.

@JoryHogeveen
Forked from eriteric/movegfjstofooter.php
Last active August 21, 2018 10:29
Show Gist options
  • Save JoryHogeveen/dae3b63d962c1fec88c552ab031522ea to your computer and use it in GitHub Desktop.
Save JoryHogeveen/dae3b63d962c1fec88c552ab031522ea to your computer and use it in GitHub Desktop.
Load gravity forms JS in footer
<?php
// GF method: http://www.gravityhelp.com/documentation/gravity-forms/extending-gravity-forms/hooks/filters/gform_init_scripts_footer/
add_filter( 'gform_init_scripts_footer', '__return_true' );
// solution to move remaining JS from https://bjornjohansen.no/load-gravity-forms-js-in-footer
// Force Gravity Forms to init scripts in the footer and ensure that the DOM is loaded before scripts are executed
add_filter( 'gform_cdata_open', 'wrap_gform_cdata_open', 1 );
function wrap_gform_cdata_open( $content = '' ) {
if ( ! wrap_gform_cdata() ) {
return $content;
}
$content = 'document.addEventListener( "DOMContentLoaded", function() { ' . $content;
return $content;
}
add_filter( 'gform_cdata_close', 'wrap_gform_cdata_close', 99 );
function wrap_gform_cdata_close( $content = '' ) {
if ( ! wrap_gform_cdata() ) {
return $content;
}
$content .= ' }, false );';
return $content;
}
function wrap_gform_cdata() {
if ( is_admin()
|| ( defined( 'DOING_AJAX' ) && DOING_AJAX )
|| isset( $_POST['gform_ajax'] )
|| doing_action( 'wp_footer' )
|| did_action( 'wp_footer' )
) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment