Last active
September 6, 2022 06:23
-
-
Save sabrina-zeidan/fe8797f5126b3776a202eb28bf8d115b to your computer and use it in GitHub Desktop.
To move third-party JS out of the head seamlessly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//add_action( 'wp_print_scripts', 'sz_enqueue_scripts', 10); //run later or via wp_print_scripts ot catch all scripts | |
add_action( 'wp_enqueue_scripts', 'sz_enqueue_scripts', 999); | |
function sz_enqueue_scripts(){ | |
global $wp_scripts; | |
//change dependency to load earlier | |
$handles_to_filter = array('dt-above-fold'); | |
$dependency_handle_to_add = 'wpb_composer_front_js'; //TODO: accept array | |
foreach ($handles_to_filter as $handle_to_filter){ | |
foreach( $wp_scripts->registered as $script_object) { //find script in registered by handle | |
if ($script_object->handle == $handle_to_filter){ | |
//let's add dependency | |
$script_object->deps[] = $dependency_handle_to_add; | |
} | |
} | |
} | |
//Problem: if dependancy script is in footer, and filtered script is in header, it brings the dependant up, not vice versa | |
//just bring to footer | |
$handles_to_put_in_footer = array('ultimate-modernizr','jquery_ui','jquery.vhparallax','ultimate-row-bg','jquery.ytplayer','jquery.shake'); | |
foreach ($handles_to_put_in_footer as $handle_to_filter){ | |
foreach( $wp_scripts->registered as $script_object) { //find script in registered by handle | |
if ($script_object->handle == $handle_to_filter){ | |
//let's add dependency | |
$script_object->extra['group'] = 1; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment