Skip to content

Instantly share code, notes, and snippets.

@sdempsey
Created November 3, 2015 21:42
Show Gist options
  • Save sdempsey/1bad8bf15bb782db3586 to your computer and use it in GitHub Desktop.
Save sdempsey/1bad8bf15bb782db3586 to your computer and use it in GitHub Desktop.
WordPress defer parsing of javascript.
<?php
//defer everything but jQuery
function vtl_defer_scripts( $tag, $handle ) {
if ( 'jquery' == $handle )
return $tag;
return str_replace( ' src', ' defer src', $tag );
}
if (!is_admin()) {
add_filter( 'script_loader_tag', 'vtl_defer_scripts', 10, 2 );
}
//you can defer jquery too but you need to get tricky with gravity forms
//defer everything
function vtl_defer_scripts( $tag, $handle ) {
return str_replace( ' src', ' defer src', $tag );
}
if (!is_admin()) {
add_filter( 'script_loader_tag', 'vtl_defer_scripts', 10, 2 );
}
//now we need to make sure Gravity Forms scripts aren't instantiated before
//jQuery
//move Gforms scripts to the footer
add_filter( 'gform_init_scripts_footer', '__return_true' );
//now we're going to wrap the inline scripts in DOMContentLoaded event listeners
//to ensure they aren't triggered before jQuery loads.
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;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment