Skip to content

Instantly share code, notes, and snippets.

@vburlak
Forked from eriteric/movegfjstofooter.php
Created July 30, 2020 20:16
Show Gist options
  • Save vburlak/4e215c9c73808e740ffe4c9c8fbd1718 to your computer and use it in GitHub Desktop.
Save vburlak/4e215c9c73808e740ffe4c9c8fbd1718 to your computer and use it in GitHub Desktop.
Load gravity forms JS in footer
// 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
add_filter( 'gform_cdata_open', 'wrap_gform_cdata_open' );
function wrap_gform_cdata_open( $content = '' ) {
$content = 'document.addEventListener( "DOMContentLoaded", function() { ';
return $content;
}
add_filter( 'gform_cdata_close', 'wrap_gform_cdata_close' );
function wrap_gform_cdata_close( $content = '' ) {
$content = ' }, false );';
return $content;
}
@vburlak
Copy link
Author

vburlak commented Jul 30, 2020

Hi, Found the same code aswell, here is a improvement on the AJAX calls!
EDITED: 2019-09-05

// Force Gravity Forms to init scripts in the footer and ensure that the DOM is loaded before scripts are executed.
add_filter( 'gform_init_scripts_footer', '__return_true' );
add_filter( 'gform_cdata_open', 'wrap_gform_cdata_open', 1 );
add_filter( 'gform_cdata_close', 'wrap_gform_cdata_close', 99 );

function wrap_gform_cdata_open( $content = '' ) {
	if ( ! do_wrap_gform_cdata() ) {
		return $content;
	}
	$content = 'document.addEventListener( "DOMContentLoaded", function() { ' . $content;
	return $content;
}

function wrap_gform_cdata_close( $content = '' ) {
	if ( ! do_wrap_gform_cdata() ) {
		return $content;
	}
	$content .= ' }, false );';
	return $content;
}

function do_wrap_gform_cdata() {
	if (
		is_admin()
		|| ( defined( 'DOING_AJAX' ) && DOING_AJAX )
		|| isset( $_POST['gform_ajax'] )
		|| isset( $_GET['gf_page'] ) // Admin page (eg. form preview).
		|| 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